简体   繁体   中英

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

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/

You can bind an event handler to the click event on the whole document and check if the targeted element is not a button:

$(document).click(function(e){
    if(e.target.nodeName.toLowerCase() != 'button')
        $('p').hide();
});

Or here's a more "jquery" way :

 $(document).click(function(e){
    if(!$(e.target).is('button'))
        $('p').hide();
});

Live DEMO .

<p style="display: none">Hello  world</p>
<button onclick='show(event);'>Say Hello</button>

function show(e){
   $("p").show();
   e.cancelBubble = true;
   document.addEventListener('click',hide,false);
}

function hide(){
   $("p").hide();
  document.removeEventListener('click',hide,false);
}

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