Net-informations.com
SiteMap  | About    

jQuery .bind() Vs .live()



jQuery .bind() method will only apply to the items you currently have selected in your jQuery object and live() method will apply to all current matching elements, as well as any you might add in the future.

jQuery .bind() method

jQuery .bind() method attached events to elements that exist or match the selector at the time the call is made. But the issue with bind() is that it doesn’t work for elements added dynamically that matches the same selector. So, the bind() method only attach events to the current elements not future element.

jQuery .live() method

jQuery .live() method overcomes the disadvantage of bind(). It works for existing and future matching elements. Before jQuery 1.4 this was limited to the following events: click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup. This method attaches the event handler to the root level document along with the associated selector and event information. By registering this information on the document it allows one event handler to be used for all events that have bubbled up to it.

jQuery .bind() Vs. .live()

jQuery .bind() example

Consider there are several < img > elements.

After that, add some extra images (using get(), or html(), anything), then you can see the new images don't have any binding!!

Of course, since the new images didn't exist when you did the $('img').bind('click', function(){...});, but it didn't bind the event handler to them.

jQuery .live() example

Consider there are several < img > elements.

Add some extra images (using get(), or html(), anything). then you can see the new images do have the binding!!

jQuery 1.7 deprecated live() method and 1.9 has removed it. If you want to achieve the same functionality with 1.9+ you need to use a new method on() which has slightly different syntax as it's invoked on document object and the selector is passed as a parameter.

The idea for adding .on() was to create a unified event API , rather than having multiple functions for binding event; .on() replaces .bind(), .live() and .delegate().









net-informations.com (C) 2019    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.