javascripteventsonload

Why is my onload event in Javascript not working


This snippet is supposed to load the script after the body has loaded, but this code is not displaying anything on the p-tag as it is supposed 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 can't fix the bug.


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