最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Click outside menu to close it - Stack Overflow

programmeradmin1浏览0评论

Here's my function,

$(document).ready(function () {
   $('.a').click(function () {
     var here = $(this).next('.b');
    if (here.is(":visible")) {
        here.hide();
    } else {
        here.show();
    }
    return false;
  });
});

So, whenever I click the button it opens a small tab on same webpage & whenever I click it again it closes it. But once I open the tab I can't close it by just clicking somewhere on webpage apart from tab. I have to click the button again to close it.

How can I close tab just by clicking somewhere on webpage also by on the button?

Here's my function,

$(document).ready(function () {
   $('.a').click(function () {
     var here = $(this).next('.b');
    if (here.is(":visible")) {
        here.hide();
    } else {
        here.show();
    }
    return false;
  });
});

So, whenever I click the button it opens a small tab on same webpage & whenever I click it again it closes it. But once I open the tab I can't close it by just clicking somewhere on webpage apart from tab. I have to click the button again to close it.

How can I close tab just by clicking somewhere on webpage also by on the button?

Share Improve this question asked Oct 6, 2017 at 15:34 user8733268user8733268 6
  • $('body').click and hide function in here – Ferhat BAŞ Commented Oct 6, 2017 at 15:36
  • Couldn't you use .blur() ? – Unknown Commented Oct 6, 2017 at 15:36
  • Another option is to keep an overlay div in your body (transparent div with z-index less than your menu's). Now, whenever you show your menu, show this div as well. Add a click handler to this div, which closes the menu. – Mohit Bhardwaj Commented Oct 6, 2017 at 15:39
  • @Unknown How can I use .blur() – user8733268 Commented Oct 6, 2017 at 15:40
  • @FerhatBAŞ How can I do that? – user8733268 Commented Oct 6, 2017 at 15:41
 |  Show 1 more ment

6 Answers 6

Reset to default 3

I end up searching for this on almost every project, so I made this plugin:

jQuery.fn.clickOutside = function(callback){
    var $me = this;
    $(document).mouseup(function(e) {
        if ( !$me.is(e.target) && $me.has(e.target).length === 0 ) {
            callback.apply($me);
        }
    });
};

It takes a callback function and passes your original selector, so you can do this:

$('[selector]').clickOutside(function(){
    $(this).removeClass('active'); // or `$(this).hide()`, if you must
});

Nice, chainable, elegant code.

On document click, the closest helps to check whether the tab has been clicked or not:

$(document).click(function (e) {
    if($('.b').is(':visible')&&!$(e.target).closest('.b').length){
       $('.b').hide();
    }
});

You want to check for a click on the body :

$("body").click(function(e) {
  if(e.target.id !== 'menu'){
    $("#menu").hide();
  }      
});

menu would be the id of the menu.

If the body is clicked and the id of the div clicked doesn't equal that of the menu, then it closes.

Check this implementation

jQuery(document).ready(function() {
    $(document).on('click','body, #btn',function(ev){
        ev.stopPropagation()
        if(ev.target.id== "btn"){
            if($('#modal').is(':visible')) {
                  $('#modal').fadeOut();
            } else{
              $('#modal').fadeIn();
            }
          } else {
            $('#modal').fadeOut();
        }
      });
});
html, body {
  height: 100%;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">
  Click Me!
</button>

<div id="modal" style="background-color:red;display:none;">
  BLA BLA BLA
</div>

To check if the clicked element is outside of a given container, i.e. a menu, we can simply check if the event target is a child of the container. Using JQuery -

$('body').click(function(e) {

    if ( 0 === $(e.target).parents('#container-id').length ) {

        /// clicked outside -> do action

    }

})

you have to add a click listener to the parent element, like here:

    $('.parent-div').click(function() {
    //Hide the menus if visible
    });

Also because click events bubbled up from child to the parent, you can exclude the click on the child element to get bubbled up and count as the parent click too. you can achieve this like below:

    //disable click event on child element 
    $('.child-div').click(function(event){
    event.stopPropagation();
    });
发布评论

评论列表(0)

  1. 暂无评论