Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hide if clicked outside the button

I want to show a paragraph by clicking on the button with the jQuery. But when it is visible, then I want to hide it by clicking anywhere else than the button (ie. anywhere outside the button). For example, here is my code:

<p style="display: none">Hello  world</p>
<button>Say Hello</button>

jQuery:

$("button").click(function () {
    $("p").show();
});

here is jsfiddle link: http://jsfiddle.net/k9mUL/

How can I hide it by clicking outside the button? Thanks

like image 592
user966585 Avatar asked Sep 27 '11 08:09

user966585


3 Answers

You could bind a click event handler to the document, as well as the one on the button. In that event handler, hide the p element:

$("button").click(function (e) {
    $("p").show();
    e.stopPropagation();
});
$(document).click(function() {
    $("p").hide();  
});

You need to stop the propagation of the click event in the button click event, otherwise it will bubble up to the document and the p element will be hidden again straight away.

Here's a working example.

like image 181
James Allardice Avatar answered Sep 30 '22 05:09

James Allardice


You can take advantage of event bubbling by binding your handler to the click event of the document and using event.target to determine if the user clicked the button or something else in the document:

$(document).click(function(event) {
    if ($(event.target).is("button")) {
        $("p").show();
    } else {
        $("p").hide();
    }
});
like image 27
Frédéric Hamidi Avatar answered Sep 30 '22 05:09

Frédéric Hamidi


Although doing it manually is great, there is a plugin which allows you to add this functionality of it helps you:

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

like image 44
Alex KeySmith Avatar answered Sep 30 '22 06:09

Alex KeySmith