2

So, I have this HTML document

<!DOCTYPE html>
<html>
  <head>
  <title>TestPage</title>
    <script src="script.js"></script>
  </head>
  <body>
    <p id="test">Sample text</p>
  </body>
</html>

With this JS file

window.addEventListener("load", MyFunction());
function MyFunction(){
  document.getElementById("test").innerHTML = "it worked";
}

and ofcourse this doesn't work (the text isn't changed), since it loads the script before it actually loads the <p id="test"></p> element (I think). It may seem strange, but I want to change the content of some elements, after everything has loaded. I have searched, but to no avail. I'm missing something obvious here probably, but I can't seem to figure it out. Any advice would be appreciated!

Spike de Held
  • 87
  • 1
  • 6

3 Answers3

6

You're calling the function in the setup for your "load" event.

Did you mean:

window.addEventListener("load", MyFunction);

??

spender
  • 117,338
  • 33
  • 229
  • 351
1

Try:

window.onload = function () { 
    MyFunction() 
}

function MyFunction(){
    document.getElementById("test").innerHTML = "it worked";
}

Source: Execute Javascript When Page Has Fully Loaded

Community
  • 1
  • 1
Friwi
  • 482
  • 3
  • 13
-1

Simply add this to your body tag :

<body onload=myFunction()>

function myFunction(){
      document.getElementById("test").innerHTML = "it worked";
}
Vaibhav Sah
  • 142
  • 1
  • 10