Home > other >  Remove class when li already have specific class
Remove class when li already have specific class

Time:04-20

I have a mega menu and when mouseover item from menu a list is opened and first element start with 'active' class, but I need to remove this when mouseover in another .item-menu li from this list.

    <ul>
        <li >
            <ul >
                <li>a</li>
                <li>b</li>
            </ul>
        </li>
        <li >
            <ul >
                <li>c</li>
                <li>d</li>
            </ul>
        </li>
    </ul>

<script>
$(".mega-drop-down").mouseover(function (event) {
      event.preventDefault();
        $("ul.item-menu li:first-child").addClass('active');
    });
    
    $(function () {
      $('ul.item-menu li').on('mouseover', function () {
        $(this).addClass('active').siblings().removeClass('active');
      });
    });
</script>

CodePudding user response:

You can simply use the mouseover method in one function only to achieve. I have created a simple working demo as per your specification.

First menu item with an active class and as soon as you mouse over the previous one will remove the active class and add the mouseover item only and so on!

Demo:

$(".mega-drop-down ul li").mouseover(function(event) {
  event.preventDefault();
  //Remove Classes from all li's
  $(".mega-drop-down ul li").removeClass('active')
  //Add Class to the mouseover eleement only
  $(this).addClass('active')
});
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li >
    <ul >
      <li >a - hover over me</li>
      <li>b - hover over me</li>
    </ul>
  </li>
  <li >
    <ul >
      <li>c - hover over me</li>
      <li>d - hover over me</li>
    </ul>
  </li>
</ul>

CodePudding user response:

Try this I guess it may solve your purpose:

$( document ).ready(function() {
$(".mega-drop-down li").mouseover(function (event) {
      event.preventDefault();
        $(this).addClass('active');
    });
    
     $('ul.item-menu li').on('mouseleave', function () {
      $("ul.item-menu li").removeClass('active');
      });
    })
.item-menu li{
  background:tomato;
  padding:20px 20px;
}
.active{
  background:green !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
        <li >
            <ul >
                <li >a</li>
                <li>b</li>
            </ul>
        </li>
        <li >
            <ul >
                <li>c</li>
                <li>d</li>
            </ul>
        </li>
    </ul>

  • Related