The question is simply between
$("body").click(function(e){});
vs $(document).click(function(e){});
which is more efficient or advisable? Or does it depend on the situation?
Honestly I have used them both interchangeably and haven't seen any differences until I got curious and asked this question here.
If the page height is smaller than the viewport height, then clicking on the viewport below the page will not trigger the 'body'
click handler, but only the document
click handler.
Live demo: http://jsfiddle.net/simevidas/ZVgDC/
In the demo, try clicking on the area below the text, and you will see that only the document
click handler executes.
Therefore, it is better to bind the handler to the Document object.
Binding it to document
seems to be the standard practice, so I would stick with that.
document
is also much faster.
I would say it's better to bind event to document as in some cases in some browsers body may be missing.
Also the body might not cover the whole visible window (some crazy styles cause that)! I don't know if you would still get the click event in this case. So better bind it to document
.
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