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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With