Marl
Marl

Reputation: 1504

jQuery CSS: Dynamically change attributes of a class

I want to change the attribute of a class on which all element that use the class for the rest of the web application life (from start of use until the user exits the web application) will be affected.

html:

<p class="myClass">
    What?
</p>
<p class="myClass">
    Now?
</p>

css:

.myClass{
    background-color: #ffff00;    
}

js:

$(".myClass").css("background-color", "#00FFFF");
$("p").last().after("<div class='myClass'>Now!</div>");

Here is a sample

What I want to achieve from the sample is that all subsequent dynamically added myClass will have the new attribute. From the jsFiddle, you'll see that the next added element doesn't have the new attribute.

MORE:

I'm just using the color for a basis, I will implement this in larger scale, what I want to accomplish is to dynamically change the attributes of a class that will be used for the entire web app life cycle.

Upvotes: 28

Views: 96509

Answers (7)

Sulot
Sulot

Reputation: 514

In addition to what have been said, I think it would be useless to modify a css rule because the already existing elements wouldn't be modified.

<style>
.myclass{
font-size:25px;
}
</style>

<div class="myclass">I am here </div>

Now, if you modify somehow the class "myclass" itselef, it wouldn't affect "I am here", because it is not dynamically binded. Perhaps it would affect the newly created elements.

Upvotes: 0

Regular Jo
Regular Jo

Reputation: 5500

I had this same goal on mind, I use hashes + ajax to navigation recordsets and I wanted viewing preferences of recordsets to be saved easily. (I wanted links to removable if the user preferred to navigate the records with links, or invisible if they chose).

DaveInMaine's answer is great but I worry a bit about backwards compatibility so I strove for a simple solution.

By naming my table, a static element, recordTable, giving it a class of LinksOn and I can use style selectors like #recordTable.LinksOn a and #recordTable.LinksOff a with display set to none, and use a simple javascript like

javascript:$('#recordTable').toggleClass('LinksOn').toggleClass('LinksOff');

By storing the last class in a variable in a cookie, server-side session via ajax, or localStorage, I can save it between sessions if I like.

I could do this all with a single class (#recordtable and #recordtable.on, rather than on and off), but I chose to store it this way.

Upvotes: 0

DaveInMaine
DaveInMaine

Reputation: 917

I just stumbled upon this question, and thought I would chime in, even though it is almost a year old...

You actually can modify the css rules dynamically at runtime, just like any other DOM element. I don't think jQuery supports it, so you would need to use the native DOM elements directly.

You can assign titles to stylesheets to make them easier to locate in the DOM tree, but with a little forethought, it's usually not too difficult to find the rules you want. Here is a quick example from a jsfiddle based on your example.

function getStyleRule(name) {
  for(var i=0; i<document.styleSheets.length; i++) {
    var ix, sheet = document.styleSheets[i];
    for (ix=0; ix<sheet.cssRules.length; ix++) {
        if (sheet.cssRules[ix].selectorText === name)
            return sheet.cssRules[ix].style;
    }
  }
return null;
}

var rule = getStyleRule('.myClass');
rule.backgroundColor = '#0ff';

$("p").last().after("<div class='myClass'>Now!</div>");

Here is a fiddle that shows your example, updated to modify the css rule itself: http://jsfiddle.net/93wGJ/5/

For more info on the DOM for stylesheets, have a look at http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html

Upvotes: 31

Viktor S.
Viktor S.

Reputation: 12815

I would do something like below. It does not modify class, but it does what you need.

$("body").addClass("updatedClass");
$("p").last().after("<div class='myClass'>Now!</div>");

and css:

.myClass{
    background-color: #ffff00;    
}
.updatedClass .myClass {
    background-color: #00FFFF;    
}

Demo

In any case, if you want to keep this enabled for any page, you should do this with server being involved. For instance, by setting some variable into a session and than returning corresponding css based on that variable.

Or you can use cookies (check jquery cookies plugin for simpler access to cookies on client side) and modify class with inserting style tag or by adding corresponding class to body in jQuery.ready callback.

for instance, with cookies (using plugin mentioned above) code could be like this:

$("body").addClass("updatedClass");
$("p").last().after("<div class='myClass'>Now!</div>");
$.cookie('baseClass', 'updatedClass'); // set class for current session (this cookie will be deleted after user ends his session)

and than, each page should have:

$(function() {
   if($.cookie('baseClass') != null) {
        $("body").addClass($.cookie('baseClass'));// or style tag could be added here instead.
   }
})

Upvotes: 1

Jai
Jai

Reputation: 74738

Try with this: http://jsfiddle.net/tRqBV/5/

$(function () {
   $(".myClass").css("background", "green");
   $("p").last().after("<div class='myClass'>Now!</div>");

   $(document).ready(function () {
    $('div.myClass').css("background", $('p.myClass').first().css('background-color'));
   });
});

Upvotes: 0

Marcin Bobowski
Marcin Bobowski

Reputation: 1765

Try putting color change in a function:

function colorChange() {
     $(".myClass").css("background-color", "#00FFFF");
}

And call it "on load" and after You change something with jQuery.

Upvotes: 5

adeneo
adeneo

Reputation: 318182

Using the css() method changes the inline styles on already existing elements, and you can't use that to change the styles on future elements. A workaround (that I don't like very much) would be to insert a style tag:

$( "<style>.myClass {background-color : #00FFFF}</style>" ).appendTo( "head" )
$("p").last().after("<div class='myClass'>Now!</div>");

FIDDLE

Upvotes: 25

Related Questions