javascriptevent-listener

How to addEventListener to future DOM elements?


File partial.html looks like this: <button id="test">Hi I am from a partial!</button>

Partial.html is dynamically 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 can I add an event listener that will apply to future exisiting #test without doing it after it's content has been loaded and inserted into #pageArea?

(No jQuery solutions, please!)


Solution

  • Events like click bubble, so you attach the event handler to the closest non-dynamic parent, and inside the event handler you check if it was the button being clicked by seeing if it was the event's target :

    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