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?
You can use the insertRule
and addRule
(when necessary) methods to add new rules to the .abc
selector. That should affect anything in the future that gets that class applied to it.
var stylesheet = document.styleSheets[0],
selector = ".abc", rule = "{color: red}";
if (stylesheet.insertRule) {
stylesheet.insertRule(selector + rule, stylesheet.cssRules.length);
} else if (stylesheet.addRule) {
stylesheet.addRule(selector, rule, -1);
}
There is a jQuery plugin for this also: $.rule()
; It's available at https://github.com/flesler/jquery.rule
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With