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
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.
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();
}
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With