Lorraine Bernard
Lorraine Bernard

Reputation: 13400

Bind events on body or document?

Sometimes the users bind the events on $('body') and sometimes on $(document)

$(document).on('click', someAction);

$('body').on('click', someAction);

Is there some reason to prefer one to another?

Upvotes: 16

Views: 6401

Answers (4)

Vsevolod Golovanov
Vsevolod Golovanov

Reputation: 4206

html and body can be smaller than the browser viewport (they fit content by default), then you can click document outside of body.

Upvotes: 0

antonjs
antonjs

Reputation: 14318

For me, there is mainly one reason to bind the events on $(document) and not to $('body'):

no need to wait domReady (document is available before everything else)

Upvotes: 8

SpYk3HH
SpYk3HH

Reputation: 22570

There is some difference in speed, not much else. Someone has already done the work though so I'll just point you the link.

http://jsperf.com/jquery-body-vs-document-body-selector

However, in direct relation to your code there, there is one major difference. $(document).on('click', someAction); will affect anywhere on the document viewing area, whereas $('body').on('click', someAction); Might not affect as much area as body can have an independent height and width.

Upvotes: 2

jAndy
jAndy

Reputation: 235992

Short answer most likely is, no, not really.

The reason someone is doing it should always be that he requires to catch an event globally in his markup. Since the <body> tag should follow as direct sibling to <html>, all events bubbling phase will end there.

<html>
    <body>
         <div>
         </div>

Every click event on <div> would bubble up to <body> as well as <html> (if not stopped manually). So for that usecase it should not make any difference.

Upvotes: 6

Related Questions