Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 860
Jake Stainer Avatar asked Apr 04 '16 19:04

Jake Stainer


2 Answers

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")
like image 59
Alexander Capone Avatar answered Nov 14 '22 23:11

Alexander Capone


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

like image 2
Mr Lister Avatar answered Nov 14 '22 22:11

Mr Lister