Grow your CSS skills. Land your dream job.

jQuery hide menu when user clicks anywhere

  • # January 6, 2014 at 10:26 am

    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?

    # January 6, 2014 at 10:46 am

    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
    });
    
    # January 6, 2014 at 12:01 pm

    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!

    # January 7, 2014 at 6:52 am

    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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".