Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda