1

var rem = 0;

$('#labrem').on('click', function(){
 if(rem == 0){$(this).css('background', 'white'); rem = 1;}
 else{$(this).css('background', '#eee'); rem = 0;}
});
.labrem{background:#eee;cursor:pointer;}
.labrem:hover{background:white;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='labrem' id='labrem'>remember me</div>

Firstly hover the mouse over rem to see - hover works.

Then click twice on rem and hover the mouse again - hover doesn't work.

What is the holy secret here?

qadenza
  • 9,025
  • 18
  • 73
  • 126

2 Answers2

1

This behaviour is caused by using inline styles. When clicking the element twice the background will be set to either #eee or white. Because inline styles override css rules the :hover never gets applied.

To be able to persist the white classes can be used:

$('#labrem').on('click', function(){
 $(this).toggleClass('activated')
});
.labrem{background:#eee;cursor:pointer;}
.labrem:hover{background:white;}

.activated{
  background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='labrem' id='labrem'>remember me</div>
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
  • so if you change the style for `normal` state - it takes precedence over `hover` state. Vey strange. – qadenza Aug 25 '19 at 18:33
  • I am not sure what you meant. Are you referring to the inline styles or css rules? CSS rules have varying specificity. The default is the order, selectors that come later override selectors that are specified earlier. Then the more specific an selector is(`.labrem:hover` is more specific than `.labrem`) can override the order of the css rules. @qadenza – MaartenDev Aug 25 '19 at 18:36
  • My point is - clicking on `rem` - it's `normal` style is changed and not `hover` style. Hover style is untouched and it must not be the object of any `precedence`. – qadenza Aug 25 '19 at 19:01
  • You can clear the inline styles by using `$(this).css('background', '')` this will allow the `:hover` css to be applied again. @qadenza – MaartenDev Aug 25 '19 at 19:03
  • useful, thanks, but nonsense regarding taking a precedence over something not included in procedure at all - remains. Why people call this - `taking precedence` why not - `a bag`. – qadenza Aug 25 '19 at 19:07
1

inline style takes higher precedence than class selector ( specificity )

when you click once the value or rem is set equal to 1, now when you click second time it goes to else condition and set the background to #eee and you don't see hover effect as inline style takes higher precedence than class selector

Code Maniac
  • 37,143
  • 5
  • 39
  • 60