Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!