2

What is the difference between the following two JavaScript snippet code. They behave differently.

window.onload = function()
{
    mainForm.onsubmit = function(e) {
        alert("Submit");
    }
}

and

window.onload = my_func();
function my_func() {

    mainForm.onsubmit = function (e) {
        alert("Submit");
    }
}

when the following HTML code is used. Once submit button is pressed I get a message 'Submit' from the first snippet but nothing from the second one.

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="utf-8">
        <title>JS Test</title>
        <script src="test.js"></script>
    </head>
    <body>
        <form method="get" action="" id="mainForm">
            <input type="submit">
        </form>
    </body>
</html>

Thank you in advance.

user2340048
  • 187
  • 1
  • 3
  • 7
  • 7
    In your second example, you're setting `window.onload` to the return value of `my_func()`. Since `my_func` doesn't return anything, `window.onload` is `undefined`. – mbcrute Apr 09 '15 at 17:31
  • See http://stackoverflow.com/a/8227270/438992, for example. – Dave Newton Apr 09 '15 at 17:38
  • Thank you, it worked by adding the return. But I have one more question, if I remove mainForm.onsubmit = function(e) { alert("Submit"); } from window.onload = function() ... and place it outside by itself then it does not work, therefore what is the relationship between window.onload and onsubmit events or else? – user2340048 Apr 09 '15 at 17:40

1 Answers1

2

Try this

window.onload = my_func;

There's a very big difference.

window.onload = stuff() will call the stuff function and assign its return value to the onload property.

window.onload = stuff assigns the stuff function to the property onload. The browser will call that function when the load event occurs. Functions are objects. When you refer to them by their name without calling them, you're referring to the object. This would be similar to the "function pointer" you were talking about

Reference: Is there a difference between window.onload = stuff and window.onload = stuff()?

Community
  • 1
  • 1
Harsh Joshi
  • 117
  • 6