Reputation: 15673
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
.
Upvotes: 4
Views: 7365
Reputation: 140220
Overly simplified and is very far away from jQuery's event system but the basic idea is there.
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:
e.currentTarget
which is very important since this
is usually used as a reference to some instance"change"
or "submit"
etc which you took for granted with jQueryUpvotes: 5
Reputation: 21532
document.addEventListener("DOMNodeInserted", evtNewElement, false);
function evtNewElement(e) {
try {
switch(e.target.id) {
case 'alert': /* addEventListener stuff */ ; break;
default: /**/
}
} catch(ex) {}
}
Note: according to the comment of @hemlock, it seems this family of events is deprecated. We have to head towards mutation observers instead.
Upvotes: 2