Skip to content Skip to sidebar Skip to footer

Javascript Function In Html Body, Wont Work

In my document I have an onLoad function given like here in this example: In addition I added a function at the end of the document which changes s

Solution 1:

That will invoke the functions, but it doesn't assign anything useful to window.onload unless your last function happens to return a function.

You need to assign a function to window.onload that will invoke your functions when the window is ready.

window.onload = function() {
    foo();
    bar();
};

Plus, since you're putting the script at the bottom, you probably don't need the window.onload.

<script>
        foo(); bar();
    </script></body>

You should also be aware that assigning directly to window.onload will overwrite the script assigned in the <body onLoad=...>, so you shouldn't do both. Currently, the return value of bar(); is wiping out the function that invokes display();.

Getting rid of the window.onload assignment will fix that.

Solution 2:

In the first case, I don't see a reason why it shouldn't work, as long as display() is defined function with no errors.

In the second case, when assigning event handlers via DOM, you need to pass either a function reference (i.e. instead of foo() just foo) or wrap it in an anonymous function like so:

window.onload = function() {
  foo();
}

Post a Comment for "Javascript Function In Html Body, Wont Work"