Event Delegation
A Pen by Bitcollage on CodePen.
<ul id="list"> | |
<li>Button (1)</li> | |
<li>Button (2)</li> | |
<li>Button (3)</li> | |
<li>Button (4)</li> | |
<li>Button (5)</li> | |
<li>Button (6)</li> | |
<li>Button (7)</li> | |
<li>Button (8)</li> | |
</ul> |
ul#list | |
- for (var i=1; i<=8; i++) | |
li Button ( #{i} ) |
var $ = document.querySelectorAll.bind(document); | |
NodeList.prototype.get = function(index){ | |
return this[index]; | |
}; | |
Element.prototype.css = function(attr, value){ | |
if((capital = /-([a-z])/g.exec(attr))){ | |
attr = attr.replace(capital[0], capital[1].toUpperCase()); | |
} | |
this.style[attr] = value; | |
return this; | |
}; | |
Event.prototype.delegate = function(elDelegate){ | |
return this.target.localName === elDelegate ? true : false; | |
}; | |
Element.prototype.on = function(type, callback, elDelegate){ | |
this.addEventListener(type, function(e){ | |
if(e.delegate(elDelegate) && elDelegate!==void(0)){ | |
callback.apply(e.target, arguments); | |
} else if(!delegate && elDelegate===void(0)) { | |
callback.apply(this, arguments); | |
} | |
}); | |
}; | |
$('#list').get(0).on('click', function(e){ | |
this.css('background-color', '#2630a7'); | |
}, 'li'); |
Event Delegation
A Pen by Bitcollage on CodePen.
Event Delegation, jQuery like, Light Weight
A Pen by Bitcollage on CodePen.
@import "compass"; | |
ul#list { | |
width: 200px; | |
list-style-type:none; | |
margin:0; | |
li { | |
padding: 5px 10px; | |
background-color: gray; | |
color: white; | |
margin: 0 0 2px 0; | |
} | |
} |