Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript jQuery hide menu when user clicks anywhere

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #159766
    markthema3
    Participant

    I’ve built a menu with some css and a little jQuery here. How would I hide the menu when the user clicks anywhere else on the page excpet on the form elements?

    #159767
    TheDoc
    Member

    It’s funny, I almost always have to look this one up. You’ll want to do something like this:

    $(document.body).click( function() {
        closeMenu();
    });
    
    $(".dialog").click( function(e) {
        e.stopPropagation(); // this stops the event from bubbling up to the body
    });
    
    #159772
    Nate Wiley
    Participant

    Hey Mark, Adding to TheDoc’s Code Above, you’ll want to write the closeMenu() function.. Something like this.

    function closeMenu(){
      $('.dialog').fadeOut(200);
      $('.add').removeClass('active');  
    }
    
    $(document.body).click( function(e) {
         closeMenu();
    });
    
    $(".dialog").click( function(e) {
        e.stopPropagation(); // this stops the event from bubbling up to the body
    });
    

    You want to use the e.stopPropagation() in your event handler for the + button to make sure it doesn’t close itself when you’re trying to open it, or clicking on the dialog box itself.

     $('.add').click(function(e){
       e.stopPropagation(); // added this
      if ($(this).hasClass('active')){
        $('.dialog').fadeOut(200);
        $(this).removeClass('active');
      }
    

    Here’s a working fork of your pen with these changes.. Hope this helps!

    #159821
    Garrett
    Participant

    Adding to the code above, you could only create the body click event once the menu is open, that way it’s not constantly firing every time someone clicks on the page.

    $('.dialog').on('click', function(e){
        e.stopPropagation();
    
        // show menu
    
        /** This section could be moved into its own function **/
        $(document.body).on('click.menuHide', function(){
            var $body = $(this);
    
            // hide menu
    
            $body.off('click.menuHide');
        });
    });
    
Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.