简体   繁体   中英

JQuery Event for when user clicks outside a div?

Is there any event that can be called whenever the user clicks outside the div to hide that div?

I tried using $(document).click() , however that one is called even when the user clicks the link which is supposed to show the div. Hence, the click handler event shows the div, and immediately $(document).click() hides it, which means the div is never displayed.

Ideas?

You can try delegating the onclick event handler to the body element (or other suitable parent container) and test for whether the target element is the reveal link:

$("body").click(function(e) {
    if(e.target.id == "idOfLinkToShowDiv") {
        $("#idOfTheDiv").show();
    } else {
        $("#idOfTheDiv").hide();
    }
});

The above can be shortened using .toggle :

$("body").click(function(e) {
    $("#idOfTheDiv").toggle(e.target.id == "idOfLinkToShowDiv");
});

Another way:

$("body").click(function() {
    $("#idOfTheDiv").hide();
});

$(".showLink").click(function(e) {
    e.stopPropagation();
    $("#idOfTheDiv").show();
});

When any element is clicked, check if the ID of the element matches the one you want to hide. If it doesn't, hide it.

$("*").click(function(){
    if(this.id === "hideMe"){
        return false;
    }
    else{
        $("#hideMe").hide();
    }
});

Check out demo on jsFiddle

Yes. After you display the div, only then bind the click event to hide the div (to the document body). Then, on the displayed div itself, catch click() event, and prevent propagation on div click(). Any click outside the div will hide, and any click inside will not bubble to the document.

function hideDiv(){
    $('#someDiv').hide();
    $(document.body).unbind('click',hideDiv);
}

$('#someLink').click(function(){
    $('#someDiv').show().click(function(e){ e.stopPropagation(); });
    $(document.body).bind('click',hideDiv);
});

One soluation is the check which element is clicked.

Another solution might be:

<body>
  <div class="infopane"></div>
  <div class="wrapper">
    content of page
  </div>
</body>

So I can do:

$('.wrapper').click(function() {
  $('.infopane').hide();
});

You are looking for the outside events plugin. Super easy to use

http://benalman.com/projects/jquery-outside-events-plugin/

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