Skip to content
Advertisement

Function call after body.onload returns unwanted result

I have the following problem:

<body>
<script>
function myfunction(y) {
    alert(y);
    }

var x = "1";
myfunction(x);
</script>
</body>

This script gives me the desired result: 1 However, the script is executed in my code only with document.body.onload:

<body>
<script>
document.body.onload = function myfunction(y) {
    alert(y);
    }

var x = "1";
myfunction(x);
</script>
</body>

But in this case the result is not 1, but [object Event]. What do I have to do to get 1 as result?

Advertisement

Answer

I’m not sure if this is what you mean:

function myfunction(y) {
  alert(y);
}
document.body.onload = function() {
  var x = "1";
  myfunction(x);
}

Basically, if you set onload as you function which takes a parameter – the argument will be event itself, not the value you tried to provide to it

You can read more here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement