Javascript Countdown to show/hide on specified days & hours - javascript

Hi I've been trying to take and work with some code that I can get partially working, I want a countdown that we can set an end time it counts down to (obvious is obvious out of the way), we also want to set it to show at only certain times of the day and only certain days of the week.
I've managed to get the below working so we can set a time of the day to show but I can't get it to work so it only shows on the certain specified days. Can anyone help please?
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
if (d.getHours() >= 7 && d.getHours() <= 15) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
[EDIT]
Just to add to this I tried changing part of the script to this but it didn't work:
$(function() {
$("#countdown").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 1 || day == 2) {
//gets the current time.
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 10 ){
$("#countdown").show();
}
else {
$("#countdown").hide();
}
} else {
$("#countdown").hide();
}
}
});
});

Whatever you did is all good except the setInterval part where you are passing the string value as setInterval("tick()", 1000) instead of a function reference as setInterval(tick, 1000)
Also, I have updated the code as below to check the specific day along with specific hours which you had,
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
}
You can give a try below,
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval(tick, 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
$("#countdown").hide();
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>

Related

Change hourly jquery timer to daily

Hi everybody I’ve tried (and failed) to change this simple jquery code to countdown 24 hours instead of the current 1 hour. I have a function called getMinutesUntilNextHour() that should calculate and display the 24 hour countdown:
function getMinutesUntilNextHour() {
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
if (cur_secs == 60) {
cur_mins = cur_mins;
cur_secs = 0;
} else {
cur_mins = cur_mins - 1;
}
if(secs > 50){
var response = (cur_mins) + ":0" + (cur_secs);
} else if(cur_secs == 0) {
var response = (cur_mins) + ":00";
} else {
var response = (cur_mins) + ":" + (cur_secs);
}
jQuery('#time_till_hour').text(function(){
return response;
});
setTimeout(getMinutesUntilNextHour, 1000);
}
getMinutesUntilNextHour();
I added now.getHours() then cur_hours = 24 - hours but it doesn’t display correctly. Should I add something to if current hours = 0 section?
Thanks in advance for any help you may be able to offer
Perhaps you could adjust and simplify your getMinutesUntilNextHour() function in the following way:
function getMinutesUntilNextHour() {
var now = new Date();
var hours = now.getHours();
var mins = now.getMinutes();
var secs = now.getSeconds();
// Compute time remaining per unit
var cur_hours = 23 - hours;
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
// Correct zero padding of hours if needed
if(cur_hours < 10) {
cur_hours = '0' + cur_hours;
}
// Correct zero padding of minutes if needed
if(cur_mins < 10) {
cur_mins = '0' + cur_mins;
}
// Correct zero padding of seconds if needed
if(cur_secs < 10) {
cur_secs = '0' + cur_secs;
}
// Format the countdown string
var response = cur_hours + ':' + cur_mins + ':' + cur_secs;
jQuery('#time_till_hour').text(response);
setTimeout(getMinutesUntilNextHour, 1000);
}
getMinutesUntilNextHour();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="time_till_hour">
</div>
Hope that helps!

24 hour countdown script that hits 00:00 every day at 11:00

I need a 24 hour countdown on my website that resets every day at 11:00 and after that starts 24 hour cycle again.
I don't need this script to control anything, I just need it to be there for visitors to see, so when they visit for example at 10:00 the will see 1 hour left on the clock and live counting down in format: Hours, Minutes, Seconds
And I need it to ignore clients time zone.
I found similar answer, but there is 1 hour window and it resets after that, I need it to reset immediately, how can I edit it to meet my requirements?
Here's what I found (this count to 21:00 then one hour window and than starts again):
var date;
var display = document.getElementById('time');
$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});
setInterval(function() {
date = new Date(date.getTime() + 1000);
var currenthours = date.getHours();
var hours;
var minutes;
var seconds;
if (currenthours != 21){
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
display.innerHTML = hours + ':' + minutes + ':' +seconds;
} else {
display.innerHTML = 'LIVE NOW';
}
}, 1000);
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
I guess that 1 hour reset is due to validating hours alone. Try the following code:
var date;
var display = document.getElementById('time');
$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});
setInterval(function() {
date = new Date(date.getTime() + 1000);
var currenthours = date.getHours();
var currentSecs = date.getSeconds();
var hours;
var minutes;
var seconds;
if (currenthours == 23 && currentsecs == 0){
display.innerHTML = 'LIVE NOW';
} else {
if (currenthours < 23) {
hours = 22 - currenthours;
} else {
hours = 23;
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
display.innerHTML = hours + ':' + minutes + ':' +seconds;
}
}, 1000);
To get accurate day duration even during daylight saving time changes you should stick to date arithmetic.
function time() {
var d1 = new Date();
var d2 = Date.UTC(d1.getUTCFullYear(),
d1.getUTCMonth(),
d1.getUTCDate() + (d1.getUTCHours() < 11 ? 0 : 1),
11);
var dh = d2 - d1;
var hours = Math.floor(dh / 3600000);
var dm = dh - 3600000 * hours;
var min = Math.floor(dm / 60000);
var ds = dm - 60000 * min;
var sec = Math.floor(ds / 1000);
var dmilli = ds - 1000 * sec;
setTimeout(time, dmilli);
hours = ('0' + hours).slice(-2);
min = ('0' + min).slice(-2);
sec = ('0' + sec).slice(-2);
document.querySelector('#the-final-countdown p').innerHTML = hours + ':' + min + ':' + sec;
}
time();

JavaScript set future date as today

I have the below script in our website which generates a countdown timer. The dateFuture is set to todays date at midnight. Is it possible to set this as the current date so that we don't have to change this every day?
Thank you.
var today = new Date();
dateFuture = new Date(2016, 11, 16, 23, 59, 59);
function GetCount() {
dateNow = new Date();
amount = dateFuture.getTime() - dateNow.getTime();
delete dateNow;
if(amount < 0) {
document.getElementById("countbox").innerHTML = "Now!";
} else {
days = 0;
hours = 0;
mins = 0;
secs = 0;
out = "";
amount = Math.floor(amount / 1000);
days=Math.floor(amount / 86400);
amount = amount % 86400;
hours = Math.floor(amount / 3600);
amount = amount % 3600;
mins = Math.floor(amount / 60);
amount = amount % 60;
secs = Math.floor(amount);
if(days != 0) {
out += days + " day" + ((days != 1) ? "s" : "") + ", ";
}
if(days != 0 || hours != 0) {
out += hours + " hour" + ((hours != 1) ? "s" : "") + ", ";
}
if(days != 0 || hours != 0 || mins != 0) {
out += mins + " minute" + ((mins != 1) ? "s" : "") + ", ";
}
out += secs + " seconds";
document.getElementById("countbox").innerHTML = out;
setTimeout("GetCount()", 1000);
}
}
window.onload = function() { GetCount(); }
<div id="countbox"></div>
You can manipulate the date by using setHours, setMinutes, setSeconds and setMilliseconds.
var dateFuture = new Date();
dateFuture.setHours(23);
dateFuture.setMinutes(59);
dateFuture.setSeconds(59);
dateFuture.setMilliseconds(999);

Daily javascript countdown shorten to jquery

Found this daily countdown timer and edited it a little but I find it a little long and learned that Jquery is a shorter notation of javascript but don't know anything about it.
My knowledge is not advanced enough to either shorten this or change it to jquery.
I use the <body onload = "getSeconds()"> to start the daily countdown.
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
document.getElementById("countdown").innerHTML = "Daily reset: " + result;
}
Here's your code "changed to jQuery"
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
$("#countdown").html("Daily reset: " + result);
}
saving 27 bytes ... I'm sure loading 86000+ bytes of jQuery library wont negate this saving at all
a shorter implementation, imo. simpler, and no need for jQuery (even if you've already loaded it)
//a few values that come in handy when dealing with timestamps
MILLISECOND = MILLISECONDS = 1;
SECOND = SECONDS = 1000*MILLISECONDS;
MINUTE = MINUTES = 60*SECONDS;
HOUR = HOURS = 60*MINUTES;
DAY = DAYS = 24*HOURS;
TIMEZONE_OFFSET = new Date().getTimezoneOffset() * MINUTES;
var midnight = Date.now() + DAY - (Date.now() - TIMEZONE_OFFSET) % DAY;
function updateCountdown(){
//an utility to fetch the parts (hours, mins, ...) of the time
//and return a formated output
function fetch(factor, postfix){
var value = Math.floor(t/factor);
t %= factor; //beware: side-effect
//format the value
return value > 0?
value + (postfix == null? "": postfix):
"";
}
var t = midnight - Date.now(); //time till midnight
var countdown = document.querySelector("#countdown");
if(t <= 0){
countdown.innerHTML = "Please reload page for daily reset.";
location.reload();
}else{
countdown.innerHTML = [
"Daily reset:",
fetch(HOURS, " hours"),
fetch(MINUTES, " minutes"),
fetch(SECONDS, " seconds")
].join(" ");
setTimeout(updateCountdown, 200);
}
}
updateCountdown();
Edit:
how would I change the time to be resetted at
the variable midnight holds the target-timestamp I am counting to: t = midnight-Date.now()
change the target timestamp.
//a utility that gives you the timestamp for today `00:00 AM` (in your local timezone)
function today(){
var now = Date.now();
return now - (now - TIMEZONE_OFFSET) % DAY;
}
console.log( new Date( today() ) ); //today 00:00:00 GMT+yourTimeZoneOffset
define a target timezone:
var midnight = today() + 1*DAY;
var target = today() + 20*HOURS + 45*MINUTES + 59*SECONDS;
//you see how these constants get handy ;)
and compute the time to that target:
var t = target - Date.now();
the rest is the same

Countdown Timer Problems

I have been looking for a count down timer on google and can't seem to find one.
I was just wondering if anyone would be able to help.
I got given one but it displays the wrong times.
I want it to display days, hours, minutes and seconds left.
heres what I need the timer on
http://pastebin.com/fQjyRFXw
It already has the timer code there but it's all wrong, any help would be great, thank you
If it's helps here's a snippet of the Java code
var count = <?= $time['a_time'] ?>;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("clock").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Ok I see your problem. The a_time stored in database is an Unix timestamp, thus when you are counting down, you need to know how long is between now and a_time instead of only a_time.
Try this:
var count = <?= $time['a_time'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = days + "days " + hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Why not use one of the man examples on codepen such as this beautiful one
http://codepen.io/anon/pen/VeLWdz ?
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("days");
hours == 1 ? thisEl.find(".timeRefHours").text("hour") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("minute") : thisEl.find(".timeRefMinutes").text("minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("second") : thisEl.find(".timeRefSeconds").text("seconds");
if (r["format"] == "on") {
days = String(days).length >= 2 ? days : "0" + days;
hours = String(hours).length >= 2 ? hours : "0" + hours;
minutes = String(minutes).length >= 2 ? minutes : "0" + minutes;
seconds = String(seconds).length >= 2 ? seconds : "0" + seconds
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
var thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "1 April 2017 09:00:00", // Change this to your desired date to countdown to
format: "on"
});
});

Categories