Add an event to HTML elements with a specific class.
Posted
by Juan C. Rois
on Stack Overflow
See other posts from Stack Overflow
or by Juan C. Rois
Published on 2010-04-21T19:45:56Z
Indexed on
2010/04/21
20:13 UTC
Read the original article
Hit count: 266
addeventlistener
Hello everybody, I'm working on a modal window, and I want to make the function as reusable as possible. Said that, I want to set a few anchor tags with a class equals to "modal", and when a particular anchor tag is clicked, get its Id and pass it to a function that will execute another function based on the Id that was passed. This is what I have so far:
// this gets an array with all the elements that have a class equals to "modal"
var anchorTrigger = document.getElementsByClassName('modal');
Then I tried to set the addEventListener for each item in the array by doing this:
var anchorTotal = anchorTrigger.length;
for(var i = 0; i < anchorTotal ; i++){
anchorTrigger.addEventListener('click', fireModal, false);
}
and then run the last function "fireModal" that will open the modal, like so:
function fireModal(){
//some more code here ...
}
My problem is that in the "for" loop, I get an error saying that anchorTrigger.addEvent ... is not a function. I can tell that the error might be related to the fact that I'm trying to set up the "addEventListener" to an array as oppose to individual elements, but I don't know what I'm supposed to do. Any help would be greatly appreciated.
© Stack Overflow or respective owner