sb2021
sb2021

Reputation: 31

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?

Upvotes: 1

Views: 539

Answers (2)

ashutosh887
ashutosh887

Reputation: 1

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

Also, non-interactive elements with click handlers must be avoided. A good practice!

Upvotes: 0

Rifky Niyas
Rifky Niyas

Reputation: 2046

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>

Upvotes: 1

Related Questions