Onclick Javascript event

Asked

Viewed 535 times

0

I’m testing the Onclick on JS and I’m weirding a deal, it works only when I glue the console document.querySelector('.a').onclick = teste2(); , or the first time I run/open the page. If I click on the element that I get, it doesn’t work. Why?

<html>
<head></head>
<meta charset="utf-8">
<body>

<div class="a">Testando...</div>

    <script>
      
      let teste2 = () => alert(this === window);
      document.querySelector('.a').onclick = teste2();

    </script>

</body>
</html>

1 answer

3


The method onClick receives a function so that it is instantiated when there is a click, in your example you store the function in a variable and pass it instantiated when the correct one would pass only the variable...

<html>
<head></head>
<meta charset="utf-8">
<body>

<div class="a">Testando...</div>

    <script>
      
      let teste2 = () => alert(this === window);
      document.querySelector('.a').onclick = teste2;

    </script>

</body>
</html>

  • 1

    Caraca, I mistook it with class in PHP that I can call both with teste2 and teste2(), traveled cool... Thanks Felipe!

Browser other questions tagged

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