Its no surprise that jQuery is becoming the latest poison for all Web Developers these days. I am no JavaScript expert, but jQuery makes even a scripting chimp like me to do some cool stuff without writing too much script! I had been playing with this library for some time and came across this small issue which took about an hour of head scratching. In my jQuery, I was adding a hover class to a <div> element. Here is the <div> as in the markup.
<div id="myDiv" class="Sample">
Stuff
</div>
Here is the Sample class
.Sample
{
background-position: 0px -141px;
}
Here is another class which I am going to add with jQuery.
.Sample-hover
{
background-position: 0px -218px;
}
And finally, here is my jQuery,
$('#myDiv').addClass('Sample-hover');
This did not work until I figured out why!!!! In my CSS file the Sample-hover class was declared before Sample class. Due to this, the CSS properties were not being overridden as expected. Phew!! I wished I was a good at these things. Sigh!!
You got it all wrong. Order of classes don't matter.
ReplyDeleteWhen you do an addClass, its adds a class to the element. myDiv now contains Sample and Sample-hover.
Its now : <div id="myDiv" class="Sample Sample-hover">Stuff</div>
1. You are looking for the jQuery's toggleClass method - not addClass. Or use removeClass when using addClass.
2. You may not need JavaScript for what you are trying to do. Simply replace .Sample-hover with .Sample:hover Check out CSS Pseudo classes.
I was skeptical about this in the first place. By the way, why did the hover effect start working once I put the .Sample-hover class after .Sample? I guess my point was to explain why addClass failed in my case. Somehow the background position property was not been detected on hover!
ReplyDeleteI know about the CSS pseudo classes but situations asked me to use Javascript.
"By the way, why did the hover effect start working once I put the .Sample-hover class after .Sample"
ReplyDeleteBecause the class which then becomes class="Sample Sample-hover" and then
.Sample-hover has overridden .Sample