Search code examples
jqueryhoveraddclassremoveclass

jquery - add different class for each anchor element when hover


so I'm new into jquery and I was messing around but I ran into a problem.

I got this menubar with 5 elements and I want to add a class to each element when I hover over them.

example: When I hover over "dishes" I want to add class active, but the other 4 elements should get the class inactive. And I want to remove these classes whenever I hover out.How do I this?

thanks in advance!

jquery

   $( document ).ready(function() {
     $("nav").hover(
       function () {
          $(this).addClass("active");
       },
       function () {
          $(this).removeClass("active");
      }
     );
    });

html

    <header>
<h1>Sushi Lovers</h1>
<nav>
    <ul class="nav">
    <li> <a href="#">Dishes</a> </li>
    <li> <a href="#">Lunch</a> </li>
    <li> <a href="#">Diner</a> </li>
    <li> <a href="#">Reservations</a> </li>
    <li> <a href="#">Contact us</a> </li>
  </ul>
</nav>


Solution

  • You need to target the a tag to add the class

    Try this

        $(document).ready(function () {
        $("nav li a").hover(
    
        function () {
            $(this).addClass("active").parents('ul').find('li a').not($(this)).addClass('inactive');
        },
    
        function () {
            $(this).parents('ul').find('li a').removeClass('active inactive');
        });
    });
    

    DEMO