This is the most favourite feature of mine from MooTools. Event Delegation will be very useful when you about to add event to same element which are child element of any other elements.
Just for an example, You are about to add click event to all li elements which are child element of the ul.
In short words event delegation is the process to bind the events to parent element instead of binding events to all child elements. In Event Delegation we add such events on parent element only which actually binds to the child elements of the parent elements.
So for example, We bind one click event to UL which actually fires on all child LI elements.
First thing you have to assign event to only parent elements instead of all child events.
Second and the main thing, This will be very useful when you are dealing with dynamic content like adding or deleting elements with AJAX or any other methods. So If you have used this method then you do not have to add/bind events to newly added elements.
That event will be automatically assigned to that newly created child elements. Isn’t that useful? :)
Note: In Event Delegation we add such events on parent element only which actually binds to the child elements of the parent elements.
In this article I am going to cover Event Delegation with MooTools, Later on I will cover using jQuery too. ;)
With MooTools 1.4 Event Delegation is now included in core verison.
Lets check below HTML Code:
Now below MooTools code will perform Event Delegation on the div with id “parent_ele”. Here I will bind event to all a elements which are child of div with ID “parent_ele”.
While binding events to element we give just events like click, mouseover, etc. But with the event delegation we will pass one more thing which relay. This is the word with which we can implement Event Delegation.
Now lets see the actual code for the same.
Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.
View all posts by: Avinash