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
clickevent handler to thedocument, as well as the one on the button. In that event handler, hide thepelement:You need to stop the propagation of the
clickevent in thebuttonclick event, otherwise it will bubble up to thedocumentand thepelement will be hidden again straight away.Here’s a working example.