Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is binding a click event to document better than binding it to body?

Tags:

jquery

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.

like image 378
lock Avatar asked Mar 07 '11 02:03

lock


4 Answers

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.

like image 124
Šime Vidas Avatar answered Oct 15 '22 00:10

Šime Vidas


Binding it to document seems to be the standard practice, so I would stick with that.

document is also much faster.

like image 24
alex Avatar answered Oct 15 '22 00:10

alex


I would say it's better to bind event to document as in some cases in some browsers body may be missing.

like image 32
Slawomir Wdowka Avatar answered Oct 14 '22 23:10

Slawomir Wdowka


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.

like image 2
panzi Avatar answered Oct 14 '22 23:10

panzi