Penjimon Penjimon - 5 months ago 23
jQuery Question

jQuery dynamic background-color change is forcing "inline" style on elements that contain the class

Sup dudes,

So... here's a weird prob. The goal is to dynamically set the background-color of a class, using a color picker, where certain "div" element(s) may or may not contain that class.

The following code "kind of" works, however, elements that contain the class, (where the background-color is being changed), is for some reason changing the background-color via "inline-style". (Which makes the whole thing not work) I've tried !important and a few other things with little success. Any ideas?

Note: .secondaryB is the class with the problem.


onChange: function (hsb, hex, rgb) {
$('#colorSelector4 div').css('background-color', '#' + hex);
$('.secondaryColor').css('color', '#' + hex);
$('.secondaryColorB').css('background-color', '');
$('.secondaryColorB').css('background-color', '#' + hex);


Note: Here's what is happening in the Chrome console to elements that contain ".secondaryB".

enter image description here


Because you are applying styles directly to elements, you are using the style property on those elements and this can only translate into inline styles. There are ways of dynamically creating stylesheets however, as described here.

Given a reference to a stylesheet (e.g. from the document.styleSheets array), and a reference to the specific rule you want to change (via the stylesheet.cssRules array), you can set its style property and it will modify the stylesheet itself, instead of the inline styles. Example:

// Assuming that the rule you want is the first rule of the first stylesheet of the page
document.styleSheets[0].cssRules[0].style.backgroundColor = 'blue';