PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 7, 2022

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

 November 07, 2022     css, html, javascript, jquery, menu     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing