jQuery – .bind(), .live(), .delegate(), .on() ( and also .unbind(), .die(), .undelegate(), .off() )

Confused, Which one to use, jQuery .bind(), .live(), .delegate(), .on() - Shemeer

The .bind() method registers the type of event and an event handler directly to the DOM element. The .bind() doesn’t work for elements added dynamically that matches the same selector. This method is pretty easy and quick to wire-up event handlers. The shorthand methods like .click(), .hover(), etc make it even easier to wire-up event handlers. There is a performance issue while working with large selection as the method attaches the same event handler to every matched element in the selection.The attachment is done upfront which can have performance issues on page load.

The basic difference between .bind() and .live() is bind will not attach the event handler to those elements which are added/appended after DOM is loaded and there is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind() method. When using .live() events always delegate all the way up to the document. This can affect performance if your DOM tree is deep. Chaining is not properly supported using .live() method. Using event.stopPropagation() is no longer helpful because the event has already delegated all the way up to the document. .live() method is deprecated as of jQuery 1.7 and removed from jQuery 1.9.

The .delegate() method is very powerful, The difference between .live() and .delegate() is, live function can’t be used in chaining. live function needs to be used directly on a selector/element. Also .delegate() works on dynamically added elements to the DOM where the selectors match. Chaining is supported correctly in .delegate().

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. Brings uniformity to the various event binding methods. but as the the way we call .on() method the behaviour also changes.

Note: If you are using jQuery 1.7+ then its advised to use .on() for attaching events to elements or selectors.

Read more from CodeProject.

Advertisements

One thought on “jQuery – .bind(), .live(), .delegate(), .on() ( and also .unbind(), .die(), .undelegate(), .off() )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s