tags:

views:

457

answers:

4

i'm trying to make a checkbox that will hide a specific css class when clicked, but i also want this effect to apply to all future objects that get that specific class.

for example: i have 2 divs:

divA is of class abc

divB has no class

i want the checkbox to hide all divs of class abc, this is easy, using $(".abc").hide(). but the problem is that if another part of the site made divB of class abc later on, then it won't be hidden. because the jquery code would've only applied to divA at the time.

what i'm trying to do is make the checkbox manipulate the global css definition of the document. so when the user clicks the checkbox, i would change the abc class to be hidden, and later whenever any div joins that class, it would be hidden.

is this possible in jquery?

+7  A: 

You can use the addRule() method to add new rules to the .abc selector. That should affect anything in the future that gets that class applied to it.

document.styleSheets[0].addRule(".abc", "display:none;");

There is a jQuery plugin for this also: $.rule(); It's available at http://plugins.jquery.com/project/Rule

Jonathan Sampson
Thanks for the answer. Though I should mention that this code will only work in IE. My app is a greasemonkey script, so after spending hours looking online, it turns out for firefox the syntax should be: document.styleSheets[0].insertRule(".abc { display:none; }", 0);
Moe Salih
A: 

I would probably handle this by having your checkbox add and remove a class form the <body> element:

$('body').toggleClass('hideABC');

And have the following CSS:

body.hideABC div.abc { display:none; }
body div.abc { display:block; }

So, if elsewhere in your page a <div> gets the '.abc' class added to it, then it will take on the first CSS rule and be hidden.

81bronco
+1  A: 

Here is a similar question with a good answer:

http://stackoverflow.com/questions/1079237/jquery-equivalent-of-yui-stylesheet-utility

Jourkey
Why vote me down? Especially since I think globalcss is a better plugin than rule.
Jourkey
A: 

Use live() to bind http://docs.jquery.com/Events/live

"Added in jQuery 1.3: Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events."

Bobby
I believe live is for events, not css manipulation.
Joel Potter
live binds functions to events, so the function could be to manipulate the css, correct?
Bobby
like this:$("foo").live("click", function(){ $(".abc").hide() });
Bobby
I don't believe this work work. from reading the documentation, your code would bind the click event to all future FOO objects. It will NOT apply the hide() function to all future .abc objects.
Moe Salih