Skip to content Skip to sidebar Skip to footer

Modifying Css Properties Associated To A Given Css Class Using Javascript

I have a JavaScript color picker linked to a text input. I would like several colored elements on my to change their color on the update of that color input. I could create several

Solution 1:

Totally possible, and yes it will be updated in real time.

Here is a function to do the class property update, tied to a mouseover event (requires jQuery 1.0+). Mousing over div with id myDiv will update the CSS background color to white for all div's with class myColorDivs:

$('#myDiv').mouseover(function() {

    $('.myColorDivs').css('background', '#fff');

});

Solution 2:

Sorry, i'm late ... Had the same question some days before and didn't find a practical answer. Here's how I solved it for me (requires jquery):

Add an inline-stylesheet after all other stylesheets your page may need with the class you want to change. Assign a TITLE Attribute to this stylesheet!

<styletitle="tomrulez"type="text/css">/*the stylesheet to change - Note the TITLE*/.shaded{
    color:green;
}
</style>

Add this function:

functionmodCSS (stylesheet, rule, attrib, newval){
    $.each( document.styleSheets, function( skey, svalue ) {
        if(svalue.title==stylesheet){
            $.each(svalue.cssRules,function (rkey,rvalue){
                if (rvalue.selectorText==rule){
                    rvalue.style[attrib]=newval;
                }
            });
        }
    });
  }

call it like this:

<divonclick="modCSS('tomrulez','.shaded','color','red')"> click here</div>

Parameters are:

  • stylesheet -> the TITLE of the last stylesheet on your page
  • rule -> The CSS-rule you want to change
  • attrib -> The attribute of the rule you want the change
  • newval -> The new value you want to assign to that attribute

I've tested this with Firefox, Chrome and IE10. IE may not work in older Versions. But I develop mainly backends for a small group of users that do not use IE if i tell them (Yep, i'm a lucky about that!)

Btw. Here is a Plunker that works for me: http://plnkr.co/edit/EMDpjU06U2p83Df8Lolq?p=preview

Post a Comment for "Modifying Css Properties Associated To A Given Css Class Using Javascript"