Reputation: 45
My first code working but second code not working after adding () parenthesis after myFunction. What is the reason?
Code1
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction;
</script>
<h3 id="status"></h3>
Code 2
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
Upvotes: 0
Views: 45
Reputation: 1142
window.onload is an event handler and must be a function, not the result of function. of course you may leave parenthesis, but in this way your function myFunction should return another function
<script type="text/javascript">
function myFunction(){
return function() {
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
Upvotes: 0
Reputation: 59252
In first case you're assigning the reference of the function which will be used in callback.
In your second case you're assigning the value that is being returned by the function
which is in this case undefined
as you're not returing anything.
window.onload
or any event handler for that matter, expects a function reference to be executed on callback.
Upvotes: 1