I noticed if I change the css of an element using jquery, it removes some css rules already specified to the element.
For example,
.className, .className2, etc... {
background-color: black;
color : silver;
}
.className:hover, .className2:hover, etc... {
background-color: gray;
color : white;
}
Now, if the user clicks this element, I want it to permanently change the background to show it has been clicked, and if another sibling element has been click, it will lose its jQuery-set css rules and go back to the original css-specified rules (aka, it will lose its rgba background, and the "hover" rules will be added back)
highlightClicked : function (el) {
el.css({
"background-color" : "rgba(70, 70, 70, 0.7)",
"color" : "white"
});
$('#parentElement > span').each(function () {
$($(this)).not(el).css({
"background-color" : "rgba(70, 70, 70, 0.0)",
"color" : "gray"
});
});
},
But the jquery .css seems to remove those original rules.
How can they be preserved?
Rather than use .css() to change an elements styles, a more efficient way of doing this is to add/remove a class:
HTML
//add a universal class to target with jquery, my example is .target
<div class="target className">className</div>
<div class="target className2">className2</div>
CSS
.active, .active:hover{ //don't add .active:hover if you want an actual hover state
background-color:red; //Whatever style you want
color: #FFF; //Whatever style you want
}
JQUERY
$(".target").click(function(){
$(this).addClass("active").siblings(".target").removeClass("active"); //will add the class to the clicked element and remove it from anyothers
});
EXAMPLE 1
OR if you want to change classes for an individual element, you could simply use .toggleClass() like so:
$(".target").click(function(){
$(this).toggleClass("active");
});
EXAMPLE 2
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