Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!)

like image 390
subZero Avatar asked Dec 02 '13 14:12

subZero


People also ask

Is addEventListener a DOM API?

addEventListener is a DOM Level 2 (2001) feature.

How do I grab an element from a dom?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

Can you use addEventListener with querySelectorAll?

To add an event listener to the results from the querySelectorAll method: Use the forEach() method to iterate over the collection of elements. Call the addEventListener() method on each element in the collection.


1 Answers

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

like image 173
adeneo Avatar answered Sep 22 '22 11:09

adeneo