简体   繁体   中英

How to close a menu by clicking outside the area of the open button?

A menu opens when a specific button is clicked #btn .

I would like to have the menu close, by also clicking outside the button.

Here is the FIDDLE: https://jsfiddle.net/maryisdead/rkapkoLu/

Is this possible?

Here is the javascript:

(function() {
  var btn       = $('#btn');
  menu      = $('nav ul');
  menuHeight    = menu.height();

  $(btn).on('click', function(e) {
    e.preventDefault();
    menu.slideToggle();
  });

  $(window).resize(function(){
    var w = $(window).width();
    if(w > 320 && menu.is(':hidden')) {
      menu.removeAttr('style');
    }
  });
});

You literally want to have action after clicking on something that is not #btn button.

$( document ).ready(function(){
  $('body *').not('#btn').click(function(){
     e.preventDefault();
     menu.slideToggle();
  })
});

Do not forget to unattach the event afterwards.

You can simply set listener on body

        $(".image").on('click', function(e) {
            e.preventDefault();
            menu.slideToggle();
        });

Do this

    $('html').click(function() {
menu.slideUp();
});

$('.nav-wrapper').click(function(event){
    event.stopPropagation();
});

use onblur event. It is the opposite of onfocus and is fired when the element loses the focus

onblur

I would HIGHLY recommend jQuery outsideevents http://benalman.com/projects/jquery-outside-events-plugin/

$(btn).bind("clickoutside", function(event){ // Code to hide your menu. });

It does all the work of finding everything that's "not the button" for you.

I should also mention it does a lot more than clickoutside, like you could check if they focusoutside too so if they use tab shortcuts to navigate the page the menu still closes, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM