Monday, November 7, 2022

[FIXED] How to remove toggled class when clicking outside menu

Issue

The dropdown menu is designed with CSS and HTML/JS using a class called "is-open" that is added from JS. Once present inside the HTML div specified, it will activate the CSS to display the submenu.

However there is a small issue wherein the dropdown menu once clicked will not disappear unless the same menu item is clicked. (The class will not de-toggle when clicking outside the menu-content div)

As a basic functionality this menu needs to disappear once a user clicks not just on the menu, but anywhere on the page.

My present javascript is the following:

$(document).ready(function() {
   $(".has-submenu").click(function(e) {
      e.stopPropagation();
      if($(this).hasClass("is-open")) {
         $(this).removeClass("is-open");
      } else {
         $(".has-submenu").removeClass("is-open");
         $(this).addClass("is-open");
      }
   });
});

Here is a codepen example of the code: https://codepen.io/anon/pen/EwMjrz


Solution

You could add an event listener to the document to close your menu like so

$(document).ready(function() {
  $(".has-submenu").click(function(e) {
    e.stopPropagation();
    if($(this).hasClass("is-open")) {
      $(this).removeClass("is-open");
    } else {
      $(".has-submenu").removeClass("is-open");
      $(this).addClass("is-open");
    }
  });
  $(document).on('click', function (e) {
    e.stopPropagation();
    $('.has-submenu').removeClass("is-open");
  });
});

This should do the trick!



Answered By - 3Dos
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.