Jake Stainer
Jake Stainer

Reputation: 75

Why does using jquery css background.color remove :hover?

Here is an example: https://jsfiddle.net/6kg43qfr/

Code:

Jquery:

$('#foo').css('background-color', '#f8f7f7');

Html:

<div id="foo">
test
</div>

CSS:

#foo:hover{

  background-color: red;

}

Question: Why doesn't the hover work?

Upvotes: 6

Views: 364

Answers (3)

Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

The best solution is:

#foo:hover{  
  background-color: red;  
}

#foo {
  background-color: #f8f7f7;
}

Or

You also can use this:

$('#foo').css('background-color', '#f8f7f7').hover(
function(){
    $(this).css('background-color','red');
},
function(){
    $(this).css('background-color','#f8f7f7');
});

Upvotes: 2

Alexander  Capone
Alexander Capone

Reputation: 548

That is because how you set the color in your javascript code. Inline styles has more priority then styles applied to classes or id's

There are actually many rules, of how to properly override styles. Please take a quick look at this http://www.hongkiat.com/blog/css-priority-level/

I strongly suggest you to read more about css before proceeding with the project, in order to keep code clean and maintainable.

in order to fullfill your needs, take a look at this fiddle: https://jsfiddle.net/6kg43qfr/2/

$('#foo').addClass("green-background")

Upvotes: 3

Mr Lister
Mr Lister

Reputation: 46559

Because the $('#foo').css() function puts the style in a style attribute on the element, which therefore overrides the stylesheet.

Upvotes: 2

Related Questions