I am having trouble with the window.onload
and document.onload
events. Everything I read tells me these will not trigger until the DOM is fully loa
Have you tried using a javascript library instead, e.g. jQuery and it's $(document).ready()
function:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
At the time window is loaded the body isn't still loaded therefore you should correct your code in the following manner:
<script type="text/javascript">
window.onload = function(){
window.document.body.onload = doThis; // note removed parentheses
};
function doThis() {
if (document.getElementById("myParagraph")) {
alert("It worked!");
} else {
alert("It failed!");
}
}
</script>
Tested to work in FF/IE/Chrome, although thinking about handling document.onload
too.
As already mentioned, using js-frameworks will be a far better idea.
It depends where you put the onload function (head or body tag or further down), with internal event binding seeemingly slightly different in different browsers.
See also window.onload vs document.onload
It's important to understand that ()
is an operator, just like +
or &&
. ()
Takes a function and calls it.
So in that case, doThis
is a function object, and ()
is the operator that calls the function. doThis()
combined to together calls doThis
, executes it, and evaluates to the return value of doThis
So window.onload = doThis()
is basically assigning the return value of doThis
to window.onload
And thus, to fix that, you need to reference the function itself, not call it.
Do window.onload = doThis
Just use window.onload = doThis;
instead of window.onload = doThis();