The body tag's onload attribute is really window onload. window has no
tag, so, somebody (probably in Netscape) once had the idea to make the
body tag the place to put event handlers from window. Now, event
handlers for window and body go in the body tag. It is an idea that
seems to be quite popular, even to this day.
Ian Hickson has stated that there is a benefit to having window event
handlers for body attributes and has included at least one new window
event handler as a body attribute (hashchange). Ian could not comment on
what that benefit was. I still haven't figured it out...
The following thread may help explain some more:
http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2008-September/01...
Your example's title says:
<title>
onclick behaves differently when defined via javascript
</title>
But the code has:
<body onload= "alert((document.body.onload ===
^^^^^^
So I think you might got onload mixed up with onclick.
if you would change:
<body onload= "alert(window.onload === arguments.callee)">
Op, FF, Saf (and IE, but I cannot test it).
'true'
Or,
<body onclick= "alert(window.onclick === arguments.callee)">
FF3
"true"
Because of the reasons mentioned in the whatwg thread. In firefox, the
body content handlers all map to window. I don't see this as being
invalid behavior, though it's filed as bug in Firefox.
Also, as mentioned in the whatwg thread, the event handler is really on
the window. You can trigger the event by clicking outside of the body
element (give body style="border: 1px solid" to see this in action).
We can also do one better and see that in firefox, the scope chain is
not augmented by the body element nor document.
<body onclick="alert(typeof getElementsByName)" style="border: 1px solid">
FF3:
undefined
Others:
function (or similar impl dependent string)
As we saw in an earlier thread, event handler attributes get an aug'd
scope chain, but this doesn't happen when window "wins" the event
handler attribute. In Firefox, window "wins" for all mouse events.
An event that applies to both body and window, the handler goes to window:
<body onfocus="alert(typeof getElementsByName)" style="border: 1px
solid" tabindex=1>
Best to avoid using event handler attributes in body.
For other elements, event handler attributes have the augmented scope
chain. To be fair and complete, I should also mention that event
handlers that reference other identifiers need those identifiers in the
document first (to avoid reference errors). This often means that
external script tags have to go in the head, which can slow down page
load. (Though loading strategy is a bit off-topic here). Regardless,
there are other ways of registering callbacks.
Garrett