CSS hover selector for background-color not working after dynamic change of background-color with jquery
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.
The jquery css
method adds an inline style to your elements, which means that after executing it, your div will look like
<div style="background-color: red">Hello world</div>`
Now, inline styling has always more priority than css styling, hence your problem.
So, why not adding a css class instead of using inline styling? Try with the following:
$("div").addClass("edited");
and
div:hover, div.edited:hover {
background-color: blue;
}
div.edited {
background-color: red;
}
and you'll see it works.
When you manipulate css with jQuery it adds it inline and overrides any css in a stylesheet try using jquery to add and remove a class that changes the color on hover. Here's the working fiddle: http://jsfiddle.net/KVmCt/6/
jQuery looks like this:
$("div").hover(
function(){
$(this).addClass("blue");
}
,
function(){
$(this).removeClass("blue");
});