Is CSS stylesheet stronger than jquery addClass?
Hey guys, this thing is driving me crazy. I have defined in my stylesheet:
ul#menuCnt li a {
color:"red";
}
If I want to create a hover effect using jquery will not change the color.
$("ul#menuCnt li a").hover(function() {
$(this).addClass("brown");
}, function() {
$(this).removeClass("brown");
});
I am really confused. If I don't define a color in my CSS stylesheet the hovereffect works.
I hope you can help me. You guys helped me a lot by learning jquery and css :)
Thank!
source to share
According to css priorities, if your .brown class is defined like this in your css file:
.brown{}
The rules inside will not override the same rules in the # selector.
You can override them with a keyword !important
.
.brown {
color: brown !important;
}
While not the best solution here, it will work ... The less you use, the more your code will be easier to read.
See http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html .
source to share
Why don't you use a CSS pseudoslot :hover
? For example:
#menuCnt li a {
color: "red";
}
#menuCnt li a:hover {
color: "brown";
}
Also, the use of "UL" in the selector is optional. There is no way for the page to have other elements with the ID "menuCnt", since the ID attribute must be unique in the DOM.
source to share
I did some testing with IE / FF and found that including the element id in your stylesheet (ul # menuCnt) prevents JQuery from overriding this style - at least with the methods I used (toggleClass, addClass, removeClass, etc.) ..
If you are assigning a class to an element in a tag (instead of specifying an id in your stylesheet), you can override it with JQuery.
If you remove the id from the style, you can override it with jQuery (not very useful, but useful for demonstrating behavior).
In fact, if you leave the ID in your stylesheet and try to assign a different class in the tag, you will still see the class associated with the ID in your stylesheet.
Note: Vincent's post suggests why we are seeing this behavior.
I also agree with exgum's suggestion to use: hover over your CSS.
source to share