David Walsh Blog

Event Delegation with MooTools

Events play a huge role in JavaScript. I can’t name one website I’ve created in the past two years that hasn’t used JavaScript event handling on some level. Ask yourself: how often do I inject elements into the DOM and not add an event to them? For me it’s very rare. For this reason I’m proud and excited for the release of MooTools 1.2.4’s Event.Delegation code.

WTF is Event Delegation?

Event delegation is the process of assigning an event listener to a parent for all of its children instead of assigning the same event to every child.

Some Sample HTML

<ul id="link-list">
	<li><a href="https://davidwalsh.name">David Walsh Blog Link 1</a></li>
	<li><a href="https://davidwalsh.name">David Walsh Blog Link 2</a></li>
	<li><a href="https://davidwalsh.name">David Walsh Blog Link 3</a></li>

A list with 3 list item elements which contain a link. For the sake of my example, this list will have list items added to it and we want an alert to pop up any time a link within the list is clicked.

The MooTools JavaScript Event Delegation Syntax

window.addEvent('domready',function() {
	/* delegate */
	document.id('link-list').addEvent('click:relay(a)', function(e){
		alert('you clicked a link!');
		Add link to show event delegation works!
		Notice how we haven't assigned an event to this specific element.
		We already added the event to the list element itself
	document.id('add-link').addEvent('click',function() {
		var li = new Element('li').inject('link-list');
		var link = new Element('a',{ text:'David Walsh Blog', href:'https://davidwalsh.name'}).inject(li);

All you need to do is add :relay to the parent selector and place the “children” match inside the relay pseudo selector. You’ll probably question how :relay works because the “:” syntax is used for pseudo selectors. The Element.Delegation JavaScript download overwrites the addEvent, removeEvent, and fireEvent methods to accommodate for the :relay syntax.

Event Delegation Replaces…

var links = document.id('link-list').getElements('li');
links.each(function(link) {
	link.addEvent('click',function() {
		//assign actions here

Why collect and iterate through elements to add events when you can simply use event delegation?

Event delegation is a great way to avoid repeating the same event assignments for elements within a parent element, especially when you are adding elements into the page dynamically. If you’ve not upgraded to MooTools 1.2.4 yet, I hope this is just the kick in the pants you need!