delegate method
Earlier, I mentioned that the method bindonly adds event handlers to elements that already exist in the DOM structure at the time of its action. When adding new elements, for example, using a method, appendtheir events will not be processed.
But jQuery provides a special method delegatethat allows you to create and register handlers for future elements that aren’t already in the DOM structure. This method has the following use cases:
delegate(‘selector’,’event’, event_handler): Adds a handler for the event. A selector is used to filter the elements for which a handler is added.
delegate(‘selector’,’event’, eventdata, eventhandler): same as above, plus a parameter to pass the event data to the Event object (e.data)
Using the delegate method:
1 2 3 4 5 6 7 8 9 10 11 12 | < button >Press1</ button > < button >Press2</ button > < script type = "text/javascript" > $(function(){ $('body').delegate('button','click', function(e){ $(this).css('color', 'red'); alert('Button handler: '+$(this).text()); }); $('body').append('< button >Press3</ button >'); }); </ script > |
Here, for all elements buttonthat are in the element body, a click handler is added. And despite the fact that after that a new button is added, a handler will also work for it.
We can also unregister the event handler with the undelegate:
1 | $( 'body' ).undelegate( 'button' , 'click' ); |
on method
The method onwas introduced in jQuery 1.7 and is in many ways a replacement for the delegate method and has the same effect. It has similar usage forms:
on(‘event’, ‘selector’, event_handler)
on(‘event’, ‘selector’, event_data, event_handler)
In fact, compared to the delegate method, in this case, only the selector and event parameters change:
1 2 3 4 | $( 'body' ).on( 'click' , 'button' , function (e){ $( this ).css( 'color' , 'red' ); alert( 'Button handler: ' +$( this ).text()); }); |
To unregister event handlers, you can use the method off:
1 2 3 4 | // remove click event handlers for buttons $( 'body' ).off( 'click' , 'button' ); // remove all handlers for elements inside the body tag $( 'body' ).off(); |