Ad

JavaScript/HTML: How To Use Window.onload=x Together With Body OnLoad="setTimeout('myFunction()',4000);"

- 1 answer

I'm using body onLoad="setTimeout('myFunction()',4000);" to refresh my website every 4 seconds. I want to use another JavaScript that will make my text fade. It works, but then my website won't refresh every 4 seconds. It's either fade or refresh. They interfere with each other.

The text fading Script needs window.onload=fade in order to work, but if I use it, it will overwrite the body onLoad="setTimeout('myFunction()',4000);" - how do I make both work?

Ad

Answer

You can try:

body onLoad="fade(); setTimeout(myFunction, 4000);"

instead of the window.onload call or use:

window.onload = function () {
    fade();
    setTimeout(myFunction, 4000);
};

instead of the body onload.

You could also add multiple event listeners (as they are the preferred approaches) instead of using the above methods.

function onPageLoad() {
    fade();
    setTimeout(myFunction, 4000);
    return;
};

if (document.addEventListener) {
    document.addEventListener("load", onPageLoad);
}
else if (document.attachEvent) {
    document.attachEvent("onload", onPageLoad);
}
else {
    // event handling not supported
}
Ad
source: stackoverflow.com
Ad