After jQuery fadeTo, CSS :hover stops working

Viewed 66

The div "#menu" becomes opaque after 3 seconds of loading the page.

$(function() {
    $('#menu').delay(4000).show().fadeTo('slow', 0.2);
});

In my CSS, I have a :hover-function so that the div ceases to be opaque once a mouse hovers over it:

#menu:hover {
    opacity: 1;
    transition: 1s;
}

The jQuery works fine - the div becomes opaque after 3 seconds. But then the :hover does not work anymore. Why is that so, and could anyone help me with a solution, please? Thank you!

2 Answers

The issue is because setting fadeTo() will result in the final opacity value being set on the element in an inline style. This means that you cannot easily override that style from a rule in an external stylesheet. One method is to use !important, however this is not best practice and should be avoided.

Another way would be to add a class to fade the element, allowing CSS's transition to perform the opacity fade, and then using selector specificity to override the style on :hover. Try this:

$(function() {
  setTimeout(function() {
    $('#menu').addClass('faded');
  }, 3000);
});
#menu {
  transition: opacity 0.3s;
}

#menu.faded {
  opacity: 0.2;
}

#container #menu:hover {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="menu">Menu</div>
</div>

Note that the key here is the use of the #container prefix on the :hover class to make the selector more specific. You can use whatever parent element suits your DOM structure, this is just an example.

The jQuery fadeTo method is writing an inline style of opacity: 0.2 to #menu. This is difficult to override due to how specificity is calculated.

You should instead apply a helper class (.faded) to #menu after the 4 second delay to achieve the faded effect.

That way, you can still override the opacity style on #menu:hover in plain CSS.

$('#menu').delay(4000).queue('fx', function() {
  $(this).addClass('faded');
});
#menu {
  transition: 1s;
}

#menu:hover {
  opacity: 1;
}

.faded {
  opacity: 0.2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">Menu</div>

Related