Event Delegation

EasyProgramming.net tutorial on event delegation

by Nazmus Nasir

HTML

<!-- Easy jQuery - jQuery .on() event delegation - #5 -->
<p>
Welcome to the fifth Easy jQuery Tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. In this tutorial, we'll learn about Event delegation with the .on() event method in jQuery. 
</p>
<p>
What is event delegation? It refers to the process of Event Propagataion (bubbling) to handle events at a higher level than where the event originated. It's great because it allows you to create just one single event listener for all elements that exist now or will be created in the future. For more information, check out the <a href="https://learn.jquery.com/events/event-delegation/" target="_blank">Event Delegation</a> explantion on the jQuery website.
</p>
<p>
The .on() event method looks something like <code>.on('event', 'selector', 'data', callback);</code>. 
</p>
<p>
In the above example, the item marked as 'selector' will trigger an event and be bubbled up to whatever parent you've selected.  The 'data' argument is just custom data that you can pass into the event. You don't normally see this used but we'll use it just to show you what it looks like. 
</p>
<p>
.on() examples:
</p>

<h2>
Let's practice:
</h2>
<p id="paragraph">
<span>This is Span 1</span>
<br />
<span>This is Span 2</span>
<br />
<span>This is Span 3</span>
<br />
<span>This is Span 4</span>
<br />
<span>This is Span 5</span>
<br />
<span>This is Span 6</span>
<br />
<span>This is Span 7</span>
<br />
<span>This is Span 8</span>
</p>
<br /><br /><br /><br /><br /><br /><br /><br />

CSS

td, th {
  padding: 10px;
  border-bottom: solid #000 1px;
}

JavaScript

var obj = {
	clicked: 'I\'ve been clicked',
  name: '#paragraph id'
}

$('#paragraph').on('click','span', obj ,function(e){
	$(this).css("color", "red");
  alert(e.data.name + ' : ' + $(this).text());
  console.log(e);
});