0

I'm creating a small project where there are many buttons with the same class calling the same function. I've pushed them into an array using a loop. Now, depending on the button the user presses, it should call said function, and also pass an unique parameter based on its array index.

So basically, I want to create a loop that gives all the same-classed buttons an eventListener to call the function, but with a different parameter. This is what i've tried:

let CTAs = []

for(i = 0; i < document.getElementsByClassName("CTAenabled").length; i++) {

    CTAs.push(document.getElementsByClassName("CTAenabled")[i])
    CTAs[i].addEventListener("click", () => {myFunction(i)})
} 

function myFunction(n) {
    console.log(n)
}

Using this loop, all buttons are properly pushed into the array, but when pressed, they all pass the same parameter, making the function print the same number.

Any ideas on how to give each button a different parameter according to its index?

Snirka
  • 602
  • 1
  • 5
  • 19

1 Answers1

0

Perhaps you could define an array outside of the loop that stores the values needed for the function parameter. These could be accessed with the value of i in your loop. They could also be dynamically generated in a separate for loop if needed.

let CTAs = []

let otherVals = [val1, val2, val3]

for(i = 0; i < document.getElementsByClassName("CTAenabled").length; i++) {

    CTAs.push(document.getElementsByClassName("CTAenabled")[i])
    CTAs[i].addEventListener("click", () => {myFunction(otherVals[i])})
} 

function myFunction(n) {
    console.log(n)
}
PaulC
  • 21
  • 2
  • This is a clever solution! However, turns out i just missed typing "let" at the start of the loop. Fixed that and nothing else was neccesary. – Víctor Leal Jun 30 '21 at 22:39