Home » Jquery » jquery – How to check if dropdown is toggle on and add class-Exceptionshub

jquery – How to check if dropdown is toggle on and add class-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I want to check if the dropdown menu is toggled. If the menu has a class: mega-toggle-on then add a class to id #submenu-new.

Here is my code:

  <div id="submenu-new" class="submenu-balk active" style="padding-top: 226px;">

      </div>

<script type="text/javascript">
if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).is( ".mega-toggle-on" ) ) {

 jQuery("#submenu-new").addClass("active");
alert('ss');

}
</script>

Example where you can find the mega-toggle-on class

How to&Answer:

As you are using JQuery, you can use hasClass to check whether given class is exists at the current moment and if exists you can change class to the otherClass.

if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).hasClass( "mega-toggle-on" ) ) { // class "mega-toggle-on" exists...
  jQuery("#submenu-new").addClass("active");
} else {  // class "mega-toggle-on" does not exists...
  jQuery("#submenu-new").removeClass("active");
}

Answer:

You can try like this:

if ($("#mega-menu-wrap-max_mega_menu_1 ul li").hasClass("mega-toggle-on")) {
    $("#submenu-new").addClass("active");
}

You can find documentation of hasClass of jQuery here

Answer:

You can use hasClass in jQuery

if ( jQuery( "#mega-menu-wrap-max_mega_menu_1 ul li" ).hasClass( "mega-toggle-on" ) ) {
jQuery("#submenu-new").addClass("active");
} else {
jQuery("#submenu-new").removeClass("active");}