开发者

Calling a jQuery function when clicking on "body"

I have a script that slides a div out of view when the user clicks on the background (the <body>).

Here's my cod开发者_StackOverflow社区e:

// Slide back out of view.
$('body').click(function(){
    $('.presentationArea').animate({'height': '0px'}, 1000);
});

But, see, here's the problem; If the user clicks ANYWHERE on the page, I.E. Menu links, buttons, textfields, images, the above function gets called! I only want it to be called if the user clicks the "body", you know, that thing BEHIND everything else? :) How would one do this?

Thank you


I only want it to be called if the user clicks the "body", you know, that thing BEHIND everything else? :)

You can check event.target and see if it's the actual document.body element. (Live example) But I suspect people are going to find it difficult to click that as opposed to (say) a p element, because the body doesn't typically fill the display area unless something is there to expand it (although you can do it with CSS).

But fundamentally, you can use event.target to see where the click was and decide at that point whether it's a click you want to handle (whether it was technically actually on body itself or something else you want to go ahead and treat the same way).

Alternately, you could hook up a handler to stop event bubbling via stopPropagation on all of the elements you don't want clicked — e.g., for a elements:

$('a').click(function(event) {
    event.stopPropagation();
});

stopPropagation just stops bubbling, not the default action (e.g., it doesn't keep people from following the link). But the side-effects of that might be a pain (I haven't done it globally like that, only targeted).


You should check whether e.target is the <body> element.


You are experiencing "bubbling" your click will bubble from the child element all the way up to the parent and trigger the function.

See the answer on this thread for more details:

How to stop event bubbling with jquery live?

Basically, you'll have to add a new function that on click has return false to stop the bubbling.

$('#wrapper').bind(void(0), false)

Should work assuming you have a wrapper div, as the second parameter "false" prevents bubbling.


Okay, I've got it:

  $("body").click(function(event) {  
    if(event.target.nodeName == "body" || event.target.nodeName == "BODY")
    {
      $('.presentationArea').animate({'height': '50px'}, 1000);
    }
  });


use something like this:

// Slide back out of view.
$('body').click(function(event){
    if (event.target === this) {
        $('.presentationArea').animate({'height': '0px'}, 1000);
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜