addEventListener for new elements
addeventlistener, dom-events, javascript
Solution
Overly simplified and is very far away from jQuery's event system but the basic idea is there.
http://jsfiddle.net/fJzBL/
var div = document.createElement("div"),
prefix = ["moz","webkit","ms","o"].filter(function(prefix){
return prefix+"MatchesSelector" in div;
})[0] + "MatchesSelector";
Element.prototype.addDelegateListener = function( type, selector, fn ) {
this.addEventListener( type, function(e){
var target = e.target;
while( target && target !== this && !target[prefix](selector) ) {
target = target.parentNode;
}
if( target && target !== this ) {
return fn.call( target, e );
}
}, false );
};
What you are missing on with this:
- Performance optimizations, every delegate listener will run a full loop so if you add many on a single element, you will run all these loops
- Writable event object. So you cannot fix `e.currentTarget` which is very important since `this` is usually used as a reference to some instance
- There is no data store implementation so there is no good way to remove the handlers unless you make the functions manually everytime
- Only bubbling events are supported, so no `"change"` or `"submit"` etc which you took for granted with jQuery
- Many others which I'm simply forgetting about for now
Problem
Consider a basic `addEventListener` as ``` window.onload=function(){ document.getElementById("alert") .addEventListener('click', function(){ alert("OK"); }, false); } ``` where `<div id="alert">ALERT</div>` does not exist in the original document and we call it from an external source by AJAX. How we can force `addEventListener` to work for newly added elements to the documents (after initial scan of DOM elements by `window.onload`)? In jQuery, we do this by `live()` or `delegate()`; but how we can do this with `addEventListener` in pure Javascript? As a matter of fact, I am looking for the equivalent to `delegate()`, as `live()` attaches the event to the root document; I wish to make a fresh event listening at the level of `parent`.