FFBbodie FFBbodie - 5 months ago 13
HTML Question

JavaScript counter doesn't work

I have made a JavaScript counter like this:

window.onload = 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);


HTML:

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


The browser (Google Chorme) says:

Uncaught ReferenceError: target_date is not defined


Even if I remove the
window.onload = function(){}
, the will still not work.
What have I done wrong?

Don Don
Answer

Change your first "}" to the end of the script

window.onload = 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); 
        }