Hi I am from a partial! Par...">

How to addEventListener for future dom elements?

The partial.html file is as follows: <button id="test">Hi I am from a partial!</button>

Partial.htmldynamically included on the page using XMLHttpRequest:

var oReq = new XMLHttpRequest();
oReq.open('get', 'partial.html', true);
oReq.send();
oReq.onload = function(){
        document.querySelector('#pageArea').innerHTML = this.response;
    }
}

How to add an event listener that will be applied to future exiciting #testwithout executing it after the content has been loaded and pasted into #pageArea?

(No jQuery solutions, please!)

+4
source share
1 answer

Events, such as click bubble , so you attach an event handler to the nearest non-dynamic parent, and inside the event handler you check whether this button was pressed if this was the purpose of the event:

var parent = document.getElementById('pageArea');

if (parent.addEventListener) {
    parent.addEventListener('click', handler, false);
}else if (parent.attachEvent) {
    parent.attachEvent('onclick', handler);
}

function handler(e) {
    if (e.target.id == 'test') {
         // the button was clicked
    }
}

Fiddle

+8

All Articles