Reputation: 19
If I had a function like this:
document.someElement.click = function(){alert(555);}
and I don't have in the element someElement
in the HTML page itself, so after I add someElement
to the page, but the code before doesn't work.
What is the best way to add event listeners to (new) dynamically added HTML elements?
Upvotes: 2
Views: 270
Reputation: 1074385
There are two common strategies here.
Hook the event on the element after you add the element to the DOM.
Use event delegation.
The first is fairly straightforward, so I'll focus on the second:
The idea with event delegation is that most DOM events "bubble" from the element where they occur up to the document, and you can handle them at any level.
So for instance, suppose you have
<div id="container">
</div>
You can hook the click
event on the container div, and then if you do something like this:
var span = document.createElement('span');
span.innerHTML = "Hi there";
document.getElementById("container").appendChild(span);
...then, when you click the span
, the event will bubble up to the container, and you see the click in the container's click
handler.
You can tell which element started the event by using the target
property on the event
object.
Here's an example:
HTML:
<button id="theButton">Click To Add</button>
<div id="container"></div>
JavaScript:
// Note that this code is at the end of the document
(function() {
var container = document.getElementById("container");
// Hook clicks on the button
document.getElementById("theButton").onclick = buttonClick;
// Hook clicks on the container
container.onclick = containerClick;
// Handle button clicks
function buttonClick() {
var child = document.createElement('div');
child.id = ('d' + container.childNodes.length) +
Math.floor(Math.random() * 10000);
child.innerHTML = "I'm child div '" + child.id + "'";
container.appendChild(child);
}
// Handle container clicks
function containerClick(event) {
event = event || window.event;
alert("You clicked child '" + event.target.id + "'");
}
})();
Note: I've used onclick
to keep things simple. In production, I recommend using addEventListener
(or attachEvent
on IE). In fact, I typically recommend using a good library like jQuery, YUI, Closure, or any of several others for the significant utility functionality they provide (including smoothing over the addEventListener
/ attachEvent
thing).
Upvotes: 4
Reputation: 173572
You can use addEventListener()
(attachEvent()
for IE) to register a click handler on a newly created element, for example:
var x = document.createElement('div');
x.innerText = 'click me';
x.addEventListener('click', function() {
alert('i am clicked');
});
document.body.appendChild(x);
Update
Do take a look at TJ's answer; he's basically saying that you can set up a container onto which you define a click handler; any elements that are added inside will have their events bubble up to the container. This way you only need one click handler and not one per element.
Upvotes: 2