I have seen a bit of confusion from JavaScript
developers about the real differences on bind(), live(), delegate(), and on()
methods and when they should be use or not use.
I.
The .bind() method will not attach the events which elements are bind
after the DOM fully loaded.
II.
The .live() and delegate()
methods attach the events which are dynamically added in future.
III.
Only difference between .live() and delegate(), the .live()
is not working for chaining elements but delegate()
will work for chaining elements.
For example,
$( ‘.menu li a’ ).bind( ‘click’, function( e ) {} );
$( ‘.menu li a’).click( function( e ) {} );
$( ‘.menu li a’ ).live( ‘click’, function( e ) {} );
$(‘.menu’).delegate( "li a", "click",
function( e ) {} );
Replacement of All above,
$('#container-ids').on('click', '.element', function() { });
Replacement of All above,
$('#container-ids').on('click', '.element', function() { });
The .bind()
method register an event type and handler directly to the DOM element and the .live() method attaches the event
handler to the root level of the document.
The .delegate
() method behave similar like .live ()
and only difference between .live()
and delegate(), the .live() is not working for chaining
elements but delegate() will work
for chaining elements.
In the jQuery version 1.7, the .on() method is the new replacement for
methods bind(), live() and .delegate().
The jQuery .on()
method attaches one or more than one event handlers for the selected elements
and child elements.
Actually, this method brings a lot of consistency
to the API and we all are recommending that you use .on() method. It is very useful and simple to use in the jQuery
projects.
I hope this post is helpfully
to you! Thank you!