-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?

0

5 Answers 5

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/

1

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

<body onload='yourFunction()'>
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);
}
3
  • It is just so that you don't sit with bloated code inside the onload method
    – R4nc1d
    Commented Apr 20, 2015 at 14:59
  • ah i see what you are saying, my mistake i guess i copied it weird
    – R4nc1d
    Commented Apr 20, 2015 at 15:11
  • it looks good now, removed my comment ;)
    – Wh1T3h4Ck5
    Commented Apr 20, 2015 at 19:31
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

0

If you use jQuery do like this:

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.