CSS hover selector for background-color not working after dynamic change of background-color with jquery

Justin Meltzer picture Justin Meltzer · Jan 21, 2012 · Viewed 28.2k times · Source

I dynamically change the background color of a div with the jquery .css() method. I also want to have a CSS hover selector on that same div that changes the background color. It seems that before the color is changed with jquery, the CSS hover selector works, but after the div is changed with the jquery method, the CSS hover selector no longer works. Is there a way to work around this (without using the jquery hover method)?

This is an example of what I'm talking about: http://jsfiddle.net/KVmCt/1/

Answer

David says reinstate Monica picture David says reinstate Monica · Jan 21, 2012

The problem you're experiencing is the importance of the location of the CSS information:

An external stylesheet is over-ruled by CSS in the head of the document; which is, in turn, over-ruled by CSS in the style attribute of the element. Basically the last style encountered by the browser overrides any previously specified, and otherwise-conflicting, rules (unless the keyword of !important is used).

As JavaScript, and therefore jQuery, places its CSS/styling information into the in-line style attribute of the element this always overrides conflicting styles specified elsewhere.

The places more importance on the color: red for the div, disregarding the div:hover styles.

To work around it, you can use:

div:hover {
    background-color: blue!important;
}

JS Fiddle demo.

A better solution, though, is to avoid assigning the background-color/other styles with jQuery, and simply use CSS:

div {
    background-color: red;
}

div:hover {
    background-color: blue!important;
}

Alternatively, you could use jQuery's hover() method:

$('div').css('background-color','red').hover(
    function(){
        $(this).css('background-color','blue');
    },
    function(){
        $(this).css('background-color','red');
    });

JS Fiddle demo.