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">
// Using jQuery
$(document).ready(function () {
$('.root').on('click', function (e) {
// depending on we can call necessary function (delegation)..
jsFiddle demo (uses jQuery).
//Using DOM APIs
var el = document.getElementsByClassName('root');
el[0].addEventListener('click', function(e) {
jsFiddle demo (uses DOM APIs).