Search code examples
javascripthtmlcsscountdown

Javascript countdown won't work


I am trying to make a Javascript countdown for my website, so as a start I wanted to test the best solution. I now have a code, but when I open the website nothing is on there, I think I might have done something wrong when trying to implement Javascript into html?

My code:

<!DOCTYPE html>


<html>

<head>

    <title>Home Test Countdown</title>

    <script LANGUAGE="Javascript">

    var target_date = new Date("Aug 15, 2019").getTime();

    var days, hours, minutes, seconds;

    var countdown = document.getElementById("countdown");

    setInterval(function () {

    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    countdown.innerHTML = days + "d, " + hours + "h, "
    + minutes + "m, " + seconds + "s";  

    }, 1000);

</script>

</head>

<body>

<span id="countdown"></span>

</body>

</html>

Solution

  • Since you have the script in the head, when var countdown = document.getElementById("countdown"); is executed the element is not present in the dom so countdown will be null which will result in the error Uncaught TypeError: Cannot set property 'innerHTML' of null in line countdown.innerHTML = '...'.

    One possible solution is to move your code to a window load event handler

    window.addEventListener('load', function () {
        var target_date = new Date("Aug 15, 2019").getTime();
    
        var days, hours, minutes, seconds;
    
        var countdown = document.getElementById("countdown");
    
        setInterval(function () {
            var current_date = new Date().getTime();
            var seconds_left = (target_date - current_date) / 1000;
    
            days = parseInt(seconds_left / 86400);
            seconds_left = seconds_left % 86400;
    
            hours = parseInt(seconds_left / 3600);
            seconds_left = seconds_left % 3600;
    
            minutes = parseInt(seconds_left / 60);
            seconds = parseInt(seconds_left % 60);
    
            countdown.innerHTML = days + "d, " + hours + "h, " + minutes + "m, " + seconds + "s";
        }, 1000);
    })
    

    Demo: Fiddle

    Another is to move your script to the bottom of the page after <span id="countdown"></span>