Problem
I want to run a function when the page is loaded, but I don’t want to use it in the tag.
I have a script that runs when I initialize it in the body>, like shown below:
function codeAddress() {
// code
}
<body onLoad="codeAddress()">
However, I’d like to run it without the body onload=”codeAddress()”> tag. I’ve tried a number of things, for example,
window.onload = codeAddress;
However, it isn’t working.
So, once the page has loaded, how do I run it?
Asked by Claes Gustavsson
Solution #1
window.onload = codeAddress; should work – here’s an example as well as the complete code:
Answered by Darin Dimitrov
Solution #2
Since the debut of jQuery, native JavaScript has adopted some wonderful functions instead of utilizing jQuery or window.onload. Without the usage of a jQuery library, all modern browsers now have their own DOM ready function.
If you’re using native Javascript, I’d recommend this.
document.addEventListener('DOMContentLoaded', function() {
alert("Ready!");
}, false);
Answered by Spencer May
Solution #3
I’m going to use Darin’s answer, but in a jQuery way. (I’m aware that the user requested javascript.)
running fiddle
$(document).ready ( function(){
alert('ok');
});
Answered by Eat at Joes
Solution #4
Optional solution. This is my preferred method due of its brevity and code simplicity.
(function () {
alert("I am here");
})();
This is an anonymous function, which means it has no name. The function is defined and run simultaneously in this case. Add this at the beginning or end of the body, depending on whether it should be executed before or after all of the HTML components have been loaded.
Answered by Habeeb
Solution #5
window.onload = function()… etc. isn’t a really good solution.
This will most likely work, but any other functions that are now hooked to that event will be broken. Alternatively, if another function hooks into the same event after yours, yours will be broken. So you can waste a lot of time later trying to figure out why something that used to function isn’t working any longer.
Here’s a more robust response:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
I forget where I got some of the code I’ve been using, so I can’t credit the author.
function my_function() {
// whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}
I hope this information is useful:)
Answered by Will
Post is based on https://stackoverflow.com/questions/4842590/how-to-run-a-function-when-the-page-is-loaded