Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 382
Lorraine Bernard Avatar asked Dec 03 '12 16:12

Lorraine Bernard


2 Answers

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)

like image 174
antonjs Avatar answered Sep 16 '22 16:09

antonjs


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.

like image 21
jAndy Avatar answered Sep 16 '22 16:09

jAndy