Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Events are being executed automatically

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 :)).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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++
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading