I have a script that slides a div out of view when the user clicks on the background (the <body>).
Here’s my code:
// 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
You can check
event.targetand see if it’s the actualdocument.bodyelement. (Live example) But I suspect people are going to find it difficult to click that as opposed to (say) apelement, because thebodydoesn’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.targetto see where the click was and decide at that point whether it’s a click you want to handle (whether it was technically actually onbodyitself 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
stopPropagationon all of the elements you don’t want clicked — e.g., foraelements:stopPropagationjust 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).