#tip: event handling on generated elements

I'm creating list items at run-time via Javascript and I need to respond to click events on those list items. I tried a few methods, but I couldn't get it to work in IE (any version). Just about anything works in Firefox and Safari, but IE was being a pain.

My first method was to create the li's in a big string and just do someList.innerHTML = myListItems, and then looping over the newly DOM'd items and doing something like listItems[i].addEventListener('click', handleThatClick). This worked in FF and Safari, but not in IE.

So, I figure that innerHTML probably wasn't the best, so I went to using document.createElement(li), but to no avail in IE. I used both addEventListener and just setting the .onclick property of the new element. Neither worked.

I could not figure out how to listen for clicks on those generated list items.

My solution was to, instead, listen on the list itself, which exists to begin with (it is not created at runtime). So, I addEventListener on that list and then use the passed-in event's target property to find the thing that got clicked.

for example:

<ul id="someList">

java script:
document.getElementById("someList").addEventListener('click', handleListClick);

function fillSomeList () {
// some JS that fills out #someList with <li>'s

function handleListClick (event) {
var clickedElement = event.target;
// here I can get the clicked item's id via clickedElement.id
// or, as in my case due to markup structure, clickedElement.parentNode.parentNode.id
// also note, if you want the list, or whatever element has the eventListener, use event.currentTarget


Note that you can not do this with an onclick attribute of the list, such as <li onclick="handleListClick"> because that doesn't pass and event object, so you don't have a reference to the dom element associated with that click.

I hope that helps someone struggling with stuff that works in FF/Safari, but not IE! Maybe someday we'll get jQuery through Caja :/

#tags, just in case
ie6 ie7 ie8

0 Replies

Recent Posts

in YAP