EJW EJW - 6 months ago 31
Javascript Question

why does my 'click' addEventListener getting called on pageload

I have a button with id #login and a javascript file with this line:

document.getElementById('login').addEventListener('click', 'LoginPressed()')

As a test, I made this function:

function LoginPressed(){
console.log('was login pressed already??')

And my function is getting called every time the page loads. How do I stop that from happening?

Note, I've also tried the callback not in quotes, and not as a function:

document.getElementById('login').addEventListener('click', LoginPressed())
document.getElementById('login').addEventListener('click', LoginPressed)
document.getElementById('login').addEventListener('click', 'LoginPressed')


Because you are invoking it, rather than referencing it.


 document.getElementById('login').addEventListener('click', 'LoginPressed()');

Should be this:

 document.getElementById('login').addEventListener('click', LoginPressed);

There should not be parenthesis after LoginPressed because you only want to refer the the function so that it can be known that this is the function to call later. With parenthesis there, you are invoking it right away.

There should also not be quotes around LoginPressed as this is the actual name of the function. With the quotes there, the JavaScript runtime won't recognize the function properly.

Here's your code, correctly written and working (notice how the console message does not appear until you click the button):

document.getElementById('login').addEventListener('click', LoginPressed)

function LoginPressed(){
  console.log('was login pressed already??')
<button id="login">Click Me</button>