Function running as soon as the page loads

Asked

Viewed 29 times

0

With the following codes html Java script

As soon as I load the page in the browser is already displayed the result in the console inserir a descrição da imagem aqui

Is this standard for Avascript or is there something wrong with my code? How to resolve?

  • 2

    Welcome to [en.so]! You have posted an image of the code and/or error message. Although it sounds like a good idea, it’s not! One of the reasons is that if someone wants to answer the question, they can’t copy the code and change something inside. Click on the [Edit] link and put the code/error as text. See more about this in these links - Manual on how NOT to ask questions, Post Error Message as Picture

  • 2

    About your problem, note that in this code snippet btn.addEventListener('click', teste() ) you are running the function teste() and passing as parameter the return of it, that is , null

1 answer

3

The function addEventListener expects two parameters - the event you want to listen to, and the function that should be executed when it is fired - the first you passed correctly, the second, not. When you do teste(), you are calling the function (calling it). In this case, what you want to do is pass the function itself instead.

button.addEventListener('click', test)

Now, we are passing the function as argument, and it will only be called when the event is triggered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.