jQuery $(‘body’).on() vs $(‘document’).on()

Share this article

With the new jQuery function .on() replacing .live() I’ve seen several different ways to use it. Here I take a look at the main difference between using body or document as the bound element in event delegation. If your new to event delegation it provides means of attaching events to elements not yet created with also having lower overhead when attaching events to multiple elements of the same type. For more information, and if your wondering why .live() was bad deprecated take a look at jQuery .live() vs .on() review.

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such aschange and submit do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.

Source: http://api.jquery.com/on/

Using body as the delegate

For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents. HTML handle the Drag and Drop events:
$('body').on('dragover', filesDragged).on('drop', filesDropped);

Using document as the delegate

The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready. By default, most events bubble up from the original event target to the document element.

It’s all about Speed!?

body-vs-document.png
As you can see from this jsperf using document is faster than using body as the event delegate. body-vs-document2png Again document is performing better but not much difference between .on() and .delegate() – the latter calls the former. jQuery Source.
delegate: function( selector, types, data, fn ) {
                return this.on( types, selector, data, fn );
        },

Conclusion

Ask Paul Irish. But I guess it doesn’t make much difference, I tend to use body because that’s what is in the official jQuery API documentation. Correct Usage: For example, instead of:
$("body").on("click", "#commentForm .addNew", addComment)
Use:
$("#commentForm").on("click", ".addNew", addComment).

When should you use event delegation?

1. When you bind a common handler for more elements that needs same functionality. (Ex: table row hover) * In the example, if you had to bind all rows using direct bind, you would end up creating n handler for n rows in that table. By using delegation method you could end up handling all those in 1 simple handler. 2. When you add dynamic contents more frequently in DOM (Ex: Add/remove rows from a table) Why you should not use event delegation? 1. Event delegation is slower when compared to binding the event directly to element. * It compares the target selector on every bubble it hits, the comparison will be as expensive as it is complicated. 2. No control over the event bubbling until it hits the element that it is bound to. PS: Even for dynamic contents you don’t have to use event delegation method if you are bind the handler after the contents get inserted into DOM. (If the dynamic content be added not frequently removed/re-added)

Further Reading:

Event delegation is a technique to write your handlers before the element actually exist in DOM. This method has its own disadvantages and should be used only if you have such requirements. Source: http://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document

Frequently Asked Questions (FAQs) about jQuery Body On and Document On

What is the difference between jQuery body on and document on?

jQuery body on and document on are both event handlers used in jQuery. The main difference between them lies in their scope. The ‘body on’ event handler is limited to the body element of the HTML document, meaning it only listens for events that occur within the body. On the other hand, the ‘document on’ event handler listens for events that occur anywhere within the entire HTML document, including the body and head elements.

When should I use jQuery body on instead of document on?

You should use jQuery body on when you want to handle events that occur within the body element of your HTML document. This is particularly useful when you want to limit the scope of your event handling to a specific part of your document. For instance, if you want to handle click events that occur within a specific div or section, you can use the ‘body on’ event handler.

Can I use jQuery body on and document on together?

Yes, you can use jQuery body on and document on together in the same script. This can be useful when you want to handle different types of events that occur in different parts of your HTML document. For instance, you might want to use the ‘document on’ event handler to listen for keypress events that can occur anywhere in the document, while using the ‘body on’ event handler to listen for click events that occur within a specific div or section.

How can I stop event propagation with jQuery body on or document on?

You can stop event propagation in jQuery by using the ‘event.stopPropagation()’ method. This method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. You can use this method in conjunction with either the ‘body on’ or ‘document on’ event handlers.

Why are my events not working with jQuery body on?

There could be several reasons why your events are not working with jQuery body on. One common reason is that the element you’re trying to bind the event to does not exist at the time the binding code runs. This can happen if your binding code runs before the HTML document has fully loaded. To fix this, you can use the ‘document.ready’ function to ensure your binding code only runs after the document is fully loaded.

How can I bind multiple events with jQuery body on or document on?

You can bind multiple events in jQuery by passing an object to the ‘on’ method. The object should contain pairs of event types and event handlers. This allows you to bind multiple events to the same element with a single call to the ‘on’ method.

Can I use jQuery body on or document on with dynamic elements?

Yes, you can use jQuery body on or document on with dynamic elements. This is one of the main advantages of these methods. They allow you to bind events to elements that are added to the document dynamically, after the initial page load.

How can I unbind events with jQuery body on or document on?

You can unbind events in jQuery by using the ‘off’ method. This method removes event handlers that were attached with the ‘on’ method. You can use this method to unbind events from either the body or the document.

Can I use jQuery body on or document on with other JavaScript libraries?

Yes, you can use jQuery body on or document on with other JavaScript libraries. However, you should be aware that other libraries may also use the ‘ symbol, which can cause conflicts. To avoid this, you can use jQuery’s ‘noConflict’ method to give control of the ‘ symbol back to the other library.

How can I improve performance with jQuery body on or document on?

One way to improve performance with jQuery body on or document on is by using event delegation. This involves binding the event handler to a parent element, rather than to the individual child elements. This can significantly improve performance when dealing with a large number of elements.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week