Search code examples
javascripthtmlcountdown

HTML countdown with JavaScript


I am trying to create a simple HTML countdown with JavaScript, following this example. But it is not working. I am hosting my files on 000webhost. Do you see anything wrong?

<html>
    <head>
        <script src="/js/countdown.js">
            var clock = document.getElementById("countdown-holder")
            , targetDate = new Date(2050, 00, 01); // Jan 1, 2050;
            clock.innerHTML = countdown(targetDate).toString();
            setInterval(function(){
            clock.innerHTML = countdown(targetDate).toString();
            }, 1000);
        </script>
    </head>

    <body>
        Countdown until 2050
        <h1 id="countdown-holder"></h1>
    </body>
</html> 

Solution

  • You're trying to include the /js/countdown.js file in the same script tag as the rest of the code. You should be including the file first, then using a new script tag for your code that updates the contents of the div. Like this:

    <script src="/js/countdown.js"></script>
    <script>
        var clock = document.getElementById("countdown-holder")
        , targetDate = new Date(2050, 00, 01); // Jan 1, 2050;
        clock.innerHTML = countdown(targetDate).toString();
        setInterval(function(){
        clock.innerHTML = countdown(targetDate).toString();
        }, 1000);
    </script>
    

    If that doesn't work, it could be that the script is being executed before the countdown-holder div exists. Try moving the script tags to the bottom of the file, just before </body>.