Ali
Ali

Reputation: 267077

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?

Upvotes: 1

Views: 2123

Answers (5)

wesbos
wesbos

Reputation: 26317

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

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

Upvotes: 0

karim79
karim79

Reputation: 342635

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();
});

Upvotes: 6

Jage
Jage

Reputation: 8086

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);
});

Upvotes: 1

PeeHaa
PeeHaa

Reputation: 72672

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();
});

Upvotes: 0

Peter Olson
Peter Olson

Reputation: 142921

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

Upvotes: 1

Related Questions