Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

css

hover

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/

like image 950
Justin Meltzer Avatar asked Jan 20 '12 23:01

Justin Meltzer


2 Answers

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.

like image 95
David Thomas Avatar answered Sep 21 '22 13:09

David Thomas


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.

like image 25
StefanoP Avatar answered Sep 21 '22 13:09

StefanoP