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

>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

Leave a Reply