Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
Why the function doesn't alert onclick?

I'm not too sure why the code below doesn't work in the browser. Any ideas?

<!DOCTYPE html>

<html>

<script>
  function click() {
    alert("You clicked on a paragraph");
  }
</script>

<body>
  <p onclick="click()" id="paragraph">This is a paragraph</p>
</body>

</html>

I figured out how to do the above with the document.getElementById function (see below).

<!DOCTYPE html>

<html>

<script>
  function click() {
    alert("You clicked on a paragraph");
  }
</script>

<body>
  <p id="paragraph">This is a paragraph</p>
</body>

<script>
  document.getElementById("paragraph").onclick = function() {
    click();
  }
</script>

</html>

My question is why the first approach doesn't work?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your first function doesn't work because click() is a built-in function in JavaScript which simulates a mouse-click on an element. Here is a demo. So when you click on the paragraph the built-in function is executed first instead of your function which displays the message through alert() function

Since your second function is an anonymous function it executes without any error.

To solve it simply rename it to any other name except the name of a built-in function. Refer the code snippet below for example.

<!DOCTYPE html>

<html>

<body>
  <script>
      function alertOnclick() {
        alert("You clicked on a paragraph");
      }
  </script>
  <p onclick="alertOnclick()" id="paragraph">
    This is a paragraph
  </p>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

Went through your Code @sb2021

I think it is well resolved by @rifkyniyas

But I would like to give you a suggestion. Try to place the script tag inclusions just before the closing of body tag. Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.

Something just like this

<body>
.
.
.
.
.
.
<script>...</script>
</body>

Check this out

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda