Is there a reason why the alert says undefined is loaded?
function test(object) {
var id = object.id;
alert(id + " is loaded");
}
<body id="test" onload="test(this);">
<h1>Hello World!</h1>
</body>
Is there a reason why the alert says undefined is loaded?
function test(object) {
var id = object.id;
alert(id + " is loaded");
}
<body id="test" onload="test(this);">
<h1>Hello World!</h1>
</body>
In JavaScript, the this
on the onload
event on body refers to window
instead of body
. However, the onload
on image elements (and iframe
) refers to the element itself. To get around this, I would change your code to:
test(document.body)
onload
works JavaScript:<!DOCTYPE html>
<html>
<head>
<script>
function test(object) {
console.log("" + object);
}
</script>
</head>
<body id="test" onload="test(this)">
<img src="https://www.google.org/assets/static/images/logo_googledotorg-171e7482e5523603fc0eed236dd772d8.svg" onload="test(this)" />
<h1>Hello World!</h1>
</body>
</html>
"this" in your onload function will refer to the window object, not to the body element itself. In your onload function, you'll need to do a getElementById('test') to get the body's id.
I prefer window.onload than document.body.onload because it is less obtrusive. But, both however are the same.
function test(object) {
var id = object.id;
alert(id + " is loaded");
}
window.onload = function(){ test(document.body); }
<body id="test">
<h1>Hello World!</h1>
</body>
I moved the onload event to the JavaScript.