Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

If i have a program that is adding and taking away html elements dynamically and each one of these elements needs to have an event listener is there a way to add the event listener to a variable that's easier than doing it one by one? I wanted to use an array and have each index of the array to have a event listener attached to it but that doesn't seem to work.

var1 = document.getElementById('name');
var1.addEventListener("mousedown", doMouseDown, false);

This works fine but i have about 100 elements so i was hoping there is an easier way than creating 100 individual variables. I there is an easier way to do this i would love any suggestions. :)

share|improve this question

Code repetition can usually be avoided by using loops. In this case, create a list (array) of all IDs, and loop through it:

var names = ['name1', 'name2', 'etc'];
for (var i=0; i<names.length; i++) {
    document.getElementById(name[i]).addEventListener("mousedown",
                                                             doMouseDown, false);
}

If all of your elements have no descendants, you can also bind one event to the common parent, and check the event.target property:

var names = '|name1|name2|';
document.addEventListener('mousedown', function(event) {
    // Use String.indexOf, because old IE browsers do not support Array.indexOf
    if (names.indexOf( '|' + event.target.id + '|') !== -1) doMouseDown(event);
}, false);
share|improve this answer

If all these elements are children of a container element, you can add a single event listener to the parent element to capture all these events.

See http://www.quirksmode.org/js/events_order.html for more info on the way javascript events are passed up and own the DOM tree.

share|improve this answer
Mozilla doesnt support this well - ive seen it in practice so although it is elegant solution it isnt the best solution in terms of compatability. – dudelgrincen Mar 16 '12 at 17:14
@dudelgrincen - it does if you use an abstraction layer like Mootools or jQuery to take care of browser differences. – Rob Agar Mar 16 '12 at 17:19

you can organize your elements by giving them the same name and then putting them into array using getElementsByName. Afterwards you could loop through the array and add listeners to each element.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.