Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my onload event in Javascript not working

This code is not displaying anything on the p tag as it suppose to do.

<!DOCTYPE html>
<html>
<body id="myBody">
<h1>HTML DOM Events</h1>
<h2>The onload Event</h2>

<p id="demo"></p>

<script>
document.getElementById("myBody").addEventListener("load", checkCookies);
function checkCookies() {
  var text = "This page ";
  if (navigator.cookieEnabled == true)
  {
    text = "Cookies are enabled.";
  } 
  else
  {
    text = "Cookies are not enabled.";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html> 

unlike this below


<!DOCTYPE html>
<html>
<body onload="checkCookies()">
<h1>HTML DOM Events</h1>
<h2>The onload Event</h2>

<p id="demo"></p>

<script>
function checkCookies() {
  var text = "";
  if (navigator.cookieEnabled == true)
  {
    text = "Cookies are enabled.";
  } 
  else
  {
    text = "Cookies are not enabled.";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html> 

I have tried it several times but cant decode the bug. Please help and resolve. Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change the second parameter on your addEventListener to invoke the method like so:

document.getElementById("myBody").addEventListener("load", checkCookies());

adddEventListener expects an Arrow Function Expression as it’s second argument.

Check out the MDN docs for addEventListener here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading