jQuery event handling - bind to document or 'body' element?
jquery
Solution
What is the difference performance-wise?
Almost certainly none, or more accurately, nothing measurable. `$('body')` in theory has to search the DOM for the `body` element, but that's going to be very fast. Also, since `body` is a child of `document`, it will be reached in the bubbling of the event nanoseconds before `document` is.
There are a couple of differences, though:
If you used `$('body')` in a script in the `head` and didn't delay execution of it (`ready`, etc.), `$('body')` wouldn't find anything and wouldn't hook up any handlers. `$(document)`, on the other hand, would.
If the body of the document doesn't fill the viewport, then on at least some browsers, you'll get a click on `document` but not on `body`:
$(document).on("click", function() {
$("<p>document</p>").appendTo(document.body);
});
$('body').on("click", function() {
$("<p>body</p>").appendTo(document.body);
});
body {
border-bottom: 1px solid #060;
}
<p>The line marks the bottom of <code>body</code>. Click above and below the line to see where the click was caught. (Note the line will move as we append to <code>body</code>.)</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Of course, that doesn't apply to your `$('body').on('click', '.myElement', function);` because if the click is outside `body`, it's not going to pass through a `.myElement`...
For global handlers, I use `$(document)`, never `$('body')` (or `$(document.body)`), but that may well be more from habit than reason.
Problem
I have noticed the use of `$(document)` and `$('body')` when we want to reference the entire page, especially when binding events. ``` $(document).on('click', '.myElement', function); ``` and ``` $('body').on('click', '.myElement', function); ``` What is the difference performance-wise? If `$(document)` binds the event to the entire HTML document, why do we not use `$('body')` to bind events like `click` instead? Note that this question is not referring to the use of the ready function, but the use of `.on()` or `.delegate()` binding.