Search code examples
javascriptfor-loopaddeventlistenersrc

Removing [object%20PointerEvent] from my JavaScript variable when used in a source


So basically in the bellow code I want to access the image which is related to the index of the array. Now on the console.log(i), I get "1" as there are two elements in the array.

However, when I click the "array" I get "../[object%20PointerEvent]1.png". This causes an error as the file name is 1.png not the above.

Does anyone know how I can remove the [object%20PointerEvent] so I just have the "../1.png"?

Thank you

for(let i = 0; i < array.length; i++) {
    console.log(i);
    array[i].addEventListener("click", function nextImage(i) {
        image.src = i +".png";
    });
}


Solution

  • You have two different variables named i.

    • The one defined in the for loop that you want
    • The parameter in your callback function which is passed the Event object that you get

    Rename the second one so you stop shadowing the first one. Traditional names are e or event but since you aren't using it, you could just remove it.

    Using a tool like eslint with the no-shadow rule could have caught this error for you.