JavaScript/HTML: How to use window.onload=x together with body onLoad=“setTimeout('myFunction()',4000);”

Refresh

April 2019

Views

7.3k time

1

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?

3 answers

0

Try this:

window.setInterval(myFunction, 4000);
4

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
}
1

This should work universally, although I haven't tested it :)

(function(window) {
    var _onload = window.onload;

    window.onload = function() {
        _onload && _onload();
        setTimeout(myFunction, 4000);
    }
}(this));