Search code examples
javascriptfunctiononloadcountdown

How to get my javascript function to display on page load


I have found the following script that I would like to edit and use, however i cannot seem to find out how to make the script run and display when a webpage is loaded.

http://jsfiddle.net/8Ab78/4/

function ShowTime() {
  var now = new Date();
  var hrs = 18-now.getHours();
  var mins = 60-now.getMinutes();
  var secs = 60-now.getSeconds();
      timeLeft = "" +hrs+' hours '+mins+' minutes '+secs+' seconds';
  $("#countdown").html(timeLeft);
}

;
function StopTime() {
    clearInterval(countdown);

}

ShowTime();
var countdown = setInterval(ShowTime ,1000);

Above is the link to the jsfiddle. As you can see its a simple countdown timer. I have tried using a body onload="" function, but im left scratching my head a bit. I am not very good with code so any help is appreciated. I have tried writing the function within script tags and putting the div inside the body but I really cannot get the timer to display on the webpage.

Thankyou in advanced!


Solution

  • your jsfiddle is working fine so the problem must be that you are unable to make everything work in a single html file.

    <html>
    <head>
        <title></title>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script>
    
        function ShowTime() {
              var now = new Date();
              var hrs = 18-now.getHours();
              var mins = 60-now.getMinutes();
              var secs = 60-now.getSeconds();
              timeLeft = hrs+' hours '+mins+' minutes '+secs+' seconds';
              $("#countdown").html(timeLeft);
        }
    
        function StopTime() {
            clearInterval(countdown);
        }
        </script>
    </head>
    <body onload="var countdown = setInterval(function(){ShowTime()} ,1000);">
        <div id="countdown"></div>
    </body>
    </html>