Search code examples
jquerymouseoverjquery-hovermouseenter

jQuery mouseenter mouseleave hover bug


I'm attempting to apply an opacity change on my LI elements by toggling the 'active' class, but neither mouse events or hover are working. Looks like a simple fix but i can't figure out why.

jquery

$( document ).ready(function() {
  $('nav.li').mouseenter(function() {
    $(this).addClass("active");
  });

  $('nav.li').mouseleave(function() {
    $(this).removeClass("active");
  });

  $("nav.li").hover(function () {
    $(this).toggleClass("active");
  });
});

css

nav.li.active {
  opacity: .7;
}

html

<nav>
  <ul>
    <li class="about_link">...</li>
    <li class="contact_link">...</li>
    <li>...</li>
  </ul>
</nav>

Thanks


Solution

  • Your don't need the . here between nav and li, so you can change:

    $('nav.li')
    

    to:

    $('nav li')
    

    Final code look like:

    $( document ).ready(function() {
        $("nav li").hover(function () {
            $(this).toggleClass("active");
        });
    });
    

    Your current selector $('nav.li') is matching the <nav> element with class li. You also need to change your css to:

    nav li.active {
        opacity: .7;
    }
    

    Fiddle Demo