So i decided to make a wordle clone today and wrote some basic javascript after doing some html and css. I wanted to add an event to all the elements of the array at once using forEach using the code below.
const letterCounter = 0;
Array.from(document.querySelectorAll("button")).forEach(elem => {
elem.addEventListener('click', inputLetter(elem.innerText))
})
function inputLetter(letter){
Array.from(document.querySelectorAll("letter-box"))[letterCounter].innerText = letter
letterCounter++
}
It immediately throws me an error in the console. The problem is that it is supposed to do that when I click on an element of the array, not automatically. I tried it with other elements, like displaying hello world in the console after clicking but it also executed automatically.(btw i do not need help with the code itself, I just want know why the added event is being executed automatically and also i’m a beginner so please don’t judge my code :)).
>Solution :
eventHandler should be a function, you passed a function call by mistake. Function calls are run immediately.
const letterCounter = 0;
Array.from(document.querySelectorAll("button")).forEach(elem => {
elem.addEventListener('click', () => inputLetter(elem.innerText))
})
function inputLetter(letter){
Array.from(document.querySelectorAll("letter-box"))[letterCounter].innerText = letter
letterCounter++
}