Why doesn’t the click event work?

Asked

Viewed 142 times

1

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
  <button type="button">click</button>
  <p></p>

  <script>
  
    var botao = window.document.getElementsByTagName("button")[0];
    var paragrafo = window.document.getElementsByTagName("p")[0];

    botao.onclick = function() {
      paragrafo.textContent = "Você clicou!";
    };

    botao.onclick = function() {
      window.alert("Você clicou!");
    };

  </script>

</body>
</html>

So I have this code my problem is that the first onclick not only works the second onclick, because this is happening and has to execute both?

2 answers

4


In this case you are using two onclick, then basically the second onclick that you set will be the one that will run the second onclick will replace the first, so the first onclick not only the second execution.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
  <button type="button">click</button>
  <p></p>

  <script>
  
    var botao = window.document.getElementsByTagName("button")[0];
    var paragrafo = window.document.getElementsByTagName("p")[0];

    botao.onclick = function() {
      paragrafo.textContent = "Você clicou!";
    };

    botao.onclick = function() {
      window.alert("Você clicou!");
    };

  </script>

</body>
</html>

So it doesn’t happen use instead of onclick use the addEventListener, so you can call how many event click you want!

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
  <button type="button">click</button>
  <p></p>

  <script>
  
    var botao = window.document.getElementsByTagName("button")[0];
    var paragrafo = window.document.getElementsByTagName("p")[0];

    botao.addEventListener("click", function() {
      paragrafo.textContent = "Você clicou!";
    });

    botao.addEventListener("click", function() {
      window.alert("Você clicou!");
    });

  </script>

</body>
</html>

2

Browser other questions tagged

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