Skip to content

Instantly share code, notes, and snippets.

@wbruno
Last active June 7, 2019 20:43
Show Gist options
  • Save wbruno/d520cbc016c5b7abe2e9 to your computer and use it in GitHub Desktop.
Save wbruno/d520cbc016c5b7abe2e9 to your computer and use it in GitHub Desktop.
<ul id="menu">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script type="text/javascript">
Element.prototype.is = function(elementSelector) {
switch(elementSelector[0]) {
case ".":
var er = new RegExp(elementSelector.replace(".", ""));
return this.className.match(er);
break;
case "#":
return this.getAttribute("id") === elementSelector.replace("#", "");
break;
default:
return this.tagName === elementSelector.toUpperCase();
break;
}
};
Element.prototype.delegate = function(eventName, elementSelector, cb) {
var $this = this;
$this.addEventListener(eventName, function (evt) {
var $this = evt.target;
if ($this.is(elementSelector)) {
cb.call($this, evt);
}
if ($this.parentNode.is(elementSelector)) {
cb.call($this.parentNode, evt);
}
});
};
document.getElementById('menu').delegate('click', 'li', function(event){
console.log(this, event);
console.log(this.innerHTML);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment