I am trying to create a simple mouseover effect using a combination of mouseover, mouseout, addClass, and removeClass. Basically, when the user mouses over an element, I want to apply a different border (1px dashed gray). The initial state is “1px solid white”. I have a class called “highlight” which simply has “border: 1px dashed gray” in it. I want to add that class onmouseover and remove it on onmouseout but I am unable to get the effect I want unless I use !important within the “highlight” class.
I am trying to create a simple mouseover effect using a combination of mouseover,
Share
It sounds as though you’ve got the javascript working fine as is, but it’s just a problem with the specificity of your CSS rules, which is why
!importantmakes it work.You just have to make your highlighted css rules more specific than the non-highlighted rules.
Edit with further explanation:
Let’s say the relevant parts of your HTML look like this:
and you have this CSS:
Currently, all the list items in the
ulin#someItem divwill have a white border, and nothing has the classhighlightso nothing’s grey.Through whatever means you want (in your case a hover event in jQuery), you add a class to one of the items:
The HTML will now look something like this:
So far, your Javascript and HTML are working fine, but you don’t see a grey border! The problem is your CSS. When the browser is trying to decide how to style the element, it looks at all the different selectors which target an element and the styles defined in those selectors. If there are two different selectors both defining the same style (in our case, the border colour is contested), then it has to decide which style to apply and which to ignore. It does this by means of what is known as “Specificity” – that is, how specific a selector is. As outlined in the HTML Dog article, it does this by assigning a value to each part of your selector, and the one with the highest score wins. The points are:
There are some more rules, eg: the keyword
!importantand also inline styles, but that’s mostly irrelevant for this, uhh… “lesson”. The only other thing you should know is that if two selectors have the same specificity, then the one defined later in the file wins.Going back to your problem, given the CSS we had before, we can see why it’s still not got a grey border:
As mentioned earlier, the solution is to create a more specific selector:
And to answer your question in the comments, you don’t need to change any of your javascript or HTML for this to work. If you break down that selector, what it’s saying is:
…and now, given the simple
.addClass()call that you made earlier, thelisatisfies these conditions, so the border should turn grey.