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!)
addEventListener is a DOM Level 2 (2001) feature.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With