-3

I have a script which displays seconds before showing hiding the div.

var seconds_left = 20;
var interval = setInterval(function() {
    document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
    if (seconds_left <= 0)
    {
    //alert('The video is ready to play.');
        $('#def').fadeOut('slow');
        clearInterval(interval);
    }
}, 1000);

The problem is.. even the page is not fully loaded, the counting automatically starts.

What can i do to make the counting start after the page fully loaded?

Jairus Holein
  • 53
  • 2
  • 12

5 Answers5

2

You shouldn't directly assign your onload, it will replace any existing onload. Onload is used frequently so overriding it is a bad idea. Do something like this:

window.addEventListener ? 
window.addEventListener("load",yourFunction,false) : 
window.attachEvent && window.attachEvent("onload",yourFunction);

If you can use a JS library like jQuery it will probably make things easier for you. You can use

$(document).ready(function() {
  // your code
});

Ref: https://ckon.wordpress.com/2008/07/25/stop-using-windowonload-in-javascript/

m4tt1mus
  • 1,642
  • 14
  • 24
1

Try calling it in the window.onload = function () { alert("It's loaded!") }

Example

window.onload = function () {
    someFunction();
}


function someFunction() {
    var seconds_left = 20;
    var interval = setInterval(function () {
        document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
        if (seconds_left <= 0) {
            //alert('The video is ready to play.');
            $('#def').fadeOut('slow');
            clearInterval(interval);
        }
    }, 1000);
}
R4nc1d
  • 2,923
  • 3
  • 24
  • 44
1

you can set an 'onload' event on your body tag, which runs as soon as your content finishes loading:

<body onload='yourFunction()'>
Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127
0

Here is the best way if you really want to make sure your page is fully loaded:

 $(function() {
    // work when all HTML loaded except images and DOM is ready
 });

 $(window).load(function() {
    // this is come when complete page is fully loaded, including all  
    // frames, objects and images **/
 });

Use the load function for this problem I suggest you. Have a good day

Yann Chabot
  • 4,789
  • 3
  • 39
  • 56
0

If you use jQuery do like this:

$(function(){
    //your code
});

And it's code will run after when page is loaded.

Lance
  • 764
  • 1
  • 7
  • 18