Home > Software design >  Adding class on hover to sibling element when multiple parents have same class
Adding class on hover to sibling element when multiple parents have same class

Time:01-28

I am creating a mega menu, and am trying to add a class to a sibling element when the parent is hovered over. I have an example currently but it adds the class to every child element instead of only the one that has its parent being hovered over.

$('.menu > .menu-item-has-children').on('mouseover', function(e) {
  e.preventDefault();
  $(this).parent().find('.mega-menu').toggleClass('active');
});
.mega-menu {
  background:green;
}
.mega-menu.active {
  background:blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul >
  <li >
    <a href="#">Parent</a>
    <div >
      <ul>
        <li><a href="#">Sibling</a></li>
        <li><a href="#">Sibling</a></li>
      </ul>
    </div>
  </li>
  <li >
    <a href="#">Parent</a>
    <div >
      <ul>
        <li><a href="#">Sibling</a></li>
        <li><a href="#">Sibling</a></li>
      </ul>
    </div>
  </li>
</ul>

I have also tried the following, but get console errors relating to preventDefault is not a function:

$( ".menu > .menu-item-has-children" ).each(function(index,e) {
  $(this).on("mouseover", function(){
    e.preventDefault();
    $(this).parent().find('.mega-menu').toggleClass('active');
  });
});

CodePudding user response:

You don't need javascript, you could use the :hover CSS pseudo-class and CSS selector :

.mega-menu {
  background:green;
}

a:hover   .mega-menu {
  background:blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul >
  <li >
    <a href="#">Parent</a>
    <div >
      <ul>
        <li><a href="#">Sibling</a></li>
        <li><a href="#">Sibling</a></li>
      </ul>
    </div>
  </li>
  <li >
    <a href="#">Parent</a>
    <div >
      <ul>
        <li><a href="#">Sibling</a></li>
        <li><a href="#">Sibling</a></li>
      </ul>
    </div>
  </li>
</ul>

  •  Tags:  
  • Related