2

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>

Ramesh
  • 2,297
  • 2
  • 20
  • 42
zerodrama
  • 51
  • 1
  • 6

3 Answers3

2

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)

Proof of how 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>
Neil
  • 14,063
  • 3
  • 30
  • 51
1

"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.

Chris Cousins
  • 1,862
  • 8
  • 15
0

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.

Animan
  • 312
  • 1
  • 10