I have an array of objects (specifically easelJS
images) - something like this:
var imageArray = new Array; gShape = new createjs.Shape(); // shape is something imageArray.push(gShape);
What I want to do is have an event listener instead of:
gShape.addEventListener("click", function() {alert"stuff"});
I want the program to know specifically which region is clicked so that I can send an alert box in the following way:
imageArray[index].addEventListener("click", function(){ alert " you clicked region number " + index}
To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
The addEventListener() method You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.
To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div. to add a div with a class. Then we write: const div = document.
Sure. You can just use a closure to save the index of that iteration. Otherwise there are shared by the same function scope and will give you the value of the same iteration. Creating a separate function for each will save the state of that inside the function.
var imageArray = new Array; gShape = new createjs.Shape(); // shape is something imageArray.push(gShape); // Dumped all the objects for (var i = 0; i < imageArray.length; i++) { (function(index) { imageArray[index].addEventListener("click", function() { console.log("you clicked region number " + index); }) })(i); }
or better
for(var i = 0; i < imageArray.length; i++) { imageArray[i].addEventListener("click", bindClick(i)); } function bindClick(i) { return function() { console.log("you clicked region number " + i); }; }
ES6 to the rescue
let imageArray = []; gShape = new createjs.Shape(); // shape is something imageArray.push(gShape); // Dumped all the objects for (let i = 0; i < imageArray.length; i++) { imageArray[i].addEventListener("click", function() { console.log("you clicked region number " + i); }); }
Using the let
keyword creates a block scoping for the variable in iteration and will have the correct index when the event handler is invoked.
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