Sunday, September 1, 2013

DOM Event Delegation

Event delegation can be used for handling DOM events efficiently. The basic principle behind event delegation is bubbling of events. An event handler can be attached to a parent node and any event that occurs within it's child element will bubble up if not already captured on its way to the parent node.
<div class="root">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<div>F</div>
<div>G</div>
</div>
// Using jQuery
$(document).ready(function () {
$('.root').on('click', function (e) {
alert(e.target.innerHTML);
// depending on e.target we can call necessary function (delegation)..
});
});
jsFiddle demo (uses jQuery).
//Using DOM APIs
var el = document.getElementsByClassName('root');
el[0].addEventListener('click', function(e) {
alert(e.target.innerHTML);
});
jsFiddle demo (uses DOM APIs).