MichaelMitchell
MichaelMitchell

Reputation: 1167

Setting body onload without using the <body> tag

I am trying to a function to trigger once the body loads. I know that you can do this from the body tag, but I would prefer to do this from JS if this is possible.

For example: document.getElementsByTagName('body').onload = someFunc();

This does not work for me, but I think it shows what I essentially want to do.

EDIT:

I have tried the answers, what seems to be the issue is that it is calling the function before the elements it uses in the body tag are loaded, even if I put the script tags inside the body. This is what it needs to do:

var buttonElements = document.getElementsByClassName('button');

And if I do:

alert(buttonElements)

It will pop up 0, but when I create a variable in the console, it will successfully populate it with the elements.

Upvotes: 3

Views: 10662

Answers (4)

Sarfraz
Sarfraz

Reputation: 382696

Like so:

window.onload = someFunc;

If however, your function accepts arguemnts, you would need anonymous function like this:

window.onload = function(){
    someFunc(arg1, arg2);
}

BTW, other than fix that @Pointy mentioned for your code, you can also do:

document.body.onload = someFunc;

Upvotes: 5

Jim Neff
Jim Neff

Reputation: 326

If you use jQuery:

$(document).ready(function () {
    callMyFunction();
});

Upvotes: 2

jeremy
jeremy

Reputation: 10057

Dont use quotes... "someFunc"() won't work if you try to run it anyways.

window.onload = someFunc;

Upvotes: 2

Pointy
Pointy

Reputation: 413709

What you've got will almost work, but you have to import your JavaScript at the end of the <body> tag, and you have to index the first result:

document.getElementsByTagName('body')[0].onload = someFunc;

Upvotes: 5

Related Questions