so I'm having a bit of an issue. So, I want to loop through an array of SVG objects and add an event listener to each object.
My issue is that when I try to do this with this line:
alert(myRects[i].id + ' success! '+ i);
I get an error saying id is undefined...
And then when I try it with this line... (the one in the code below):
alert(rectInstance.id + ' success! '+ i);
...it seems as if every object has the same event listener as the last object in the array. Idk if my thinking is completely off or if I'm misusing something...
As always, any help is really appreciated
var myRects;
var rectInstance;
// event listener to make sure the page has loaded before running the scrupt
window.addEventListener("load", function() {
// gets an SVG object from the inline HTML
var svgObject = document.getElementById('rectTestSvg').contentDocument;
myRects = Array.from(svgObject.querySelectorAll("rect"));
// loop through the rects array
for(var i = 0; i < myRects.length; i++)
{
// copy myRects array to a temporary object
var rectInstance = myRects[i];
//add an on click event listener to each object in the rects array
rectInstance.addEventListener('click', function(){
//pop up that proves each rect got a unique on click event
alert(rectInstance.id + ' success! '+ i);
})
// add object now with eventlistener back to myRects array
myRects[i] = rectInstance;
}
});