3

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.

MichaelMitchell
  • 1,069
  • 2
  • 13
  • 38

4 Answers4

5

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;
Pointy
  • 405,095
  • 59
  • 585
  • 614
5

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;
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

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

window.onload = someFunc;
jeremy
  • 9,965
  • 4
  • 39
  • 59
2

If you use jQuery:

$(document).ready(function () {
    callMyFunction();
});
Jim Neff
  • 326
  • 2
  • 7