SitePoint Sponsor

# Thread: Countdown to the weekend

1. ## Countdown to the weekend

Hello,

I've just joined these forums having bought one of the SitePoint books recently, and this is my first post, so I hope I've posted in the right place!

I'm currently developing a site for a marine shop and they've asked for a "count down to the weekend" panel on their homepage. Their main demographic is fun-seekers, so I can see why this is a fun feature. Unfortunately, that's where the fun has ended so far....

I can't find ANY scripts online which will count down to a specific day each week. All the scripts out there (following some fairly extensive trawling) will only seem to count down to a specific date in the futue, rather than say the code equivalent of "00:00:01 this coming saturday"

Would any of you know how I might generate this sort of count down, or where I might find one? I'm assuming Javascript would be the best codebase to use for this sort of function.

Many thanks in advance! I'm going to pour a G&T!
Cheers,

Alex

2. Code:
```function moronCode(){
var A= [], now= new Date(),
d, x, D, day= now.getDay();
if(!day&#37;6) return '';
D= new Date(now);
D.setDate(D.getDate()+6-day);
D.setHours(0, 0, 0, 0);
x= D-now;
d= Math.floor(x/8.64e7);
if(d> 1){
A.push(d+' days');
x%= 8.64e7;
}
x= Math.floor(x/1000);
if(x> 3600){
d= Math.floor(x/3600);
A.push(d+' hour'+((d> 1)? 's': ''));
x%= 3600;
}
if(x> 60){
d= Math.floor(x/60);
A.push(d+' minute'+((d> 1)? 's': ''));
x%= 60;
}
if(x> 0) A.push(x+' second'+((x> 1)? 's': ''));
return A.join(', ');
}```
alert(moronCode())

3. Welcome to SitePoint!

Yes, you posted in the correct place

I don't know any script that does exactly what you want, but I can offer you this simple script:

Code javascript:
```var now=new Date();
var Y = now.getFullYear();
var m = now.getMonth();
var d = now.getDate();

var date = new Date();
while (date.getDay() != 6) {
date = new Date(Y,m,++d);
}

var target = new Date(Y,m,d,0,0,1);```

The variable "target" that is created is a date object for the next saturday 0:00:01.
If you feed this variable to a normal javascript countdown script (so instead of setting the variable of the target date, give it the target variable) it should work.

If you have any questions don't hesitate to ask

4. Originally Posted by ScallioXTX
Welcome to SitePoint!

Yes, you posted in the correct place

I don't know any script that does exactly what you want, but I can offer you this simple script:

Code javascript:
```var now=new Date();
var Y = now.getFullYear();
var m = now.getMonth();
var d = now.getDate();

var date = new Date();
while (date.getDay() != 6) {
date = new Date(Y,m,++d);
}

var target = new Date(Y,m,d,0,0,1);```

The variable "target" that is created is a date object for the next saturday 0:00:01.
If you feed this variable to a normal javascript countdown script (so instead of setting the variable of the target date, give it the target variable) it should work.

If you have any questions don't hesitate to ask
ScallioXTX, many thanks for this. I'm really quite a novice when it comes to doing anything with Javascript. I've found a number of countdown scripts, but have no idea where to substitute the pre-written code's code for your example above. *slap wrists time!*. Everything I've tried has broken horribly.

Any ideas?
Thanks in advance for all your help.

Alex

5. Point me to a script you like and I'll show you how to embed my code

6. Hey ScallioXTX, you're a star :-)

The base script I like is at: http://www.dynamicdrive.com/dynamici...dhtmlcount.htm
I'll customise the look, obviously :-p

Cheers buddy!

Alex

7. In the top, replace the following code:

Code:
```function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}```
with

Code:
```function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
var now=new Date();
var Y = now.getFullYear();
var m = now.getMonth();
var d = now.getDate();
var date = new Date();
while (date.getDay() != 6) {
date = new Date(Y,m,++d);
}
this.targetdate = new Date(Y,m,d,0,0,1);
this.timesup=false
this.updateTime()
}```

8. Hey Scallio.

Great, thanks so much for this.
I've put it in and it works great - problem is, there seems to be a lot of bloat on that particular script, and there are still references to "Christmas" on the pre-written script. Plus, there's an irritating popup which happens when you're on the day that the count down timer counts down to...!

Any ideas what, if anything, I can cut from the script to skinny it down a little?

Cheers :-)

Alex

9. Christmas should be simple to strip out. Just remove/replace the text in the code.
The popup is generated by the alert() function, find it and remove it from the code.

10. Hi Scallio,

Brilliant, many thanks for this! It's all working nicely now - what a fantastic help you've been!

Typically, clients being clients, they've now asked that the "It is the weekend" message stay displaying from 5pm on a Friday to 11:59:59 (basically midnight) on the Sunday.
I've mod-ed the relevant bit of code to:

while (date.getDay() != 5) {
date = new Date(Y,m,++d);
}
this.targetdate = new Date(Y,m,d,17,0,0);
but am wondering where I should put a condition, to say "if it's between 5pm on a friday and midnight on a sunday, display "it's the weekend!".

Any ideas at all? Sorry, I know this is going above and beyond even more! :-)
Cheers!

Alex

11. To check if it's friday after 17:00 :

var d = new Date();
if (d.getDay() == 5 && d.getHours() > 17)

Checking if it's sunday before 23:59:59 is basically the same, you should be able to figure that one out (hint, use .getMinutes() and .getSeconds())

And then you do (pseudo code)
Code:
```if (it's later than friday 17:00 AND earlier than sunday 23:59:59) {
display "It's the weekend"
} else {
initilialize and show the timer
}```
Any questions let me know

PS. For a reference of all functions of the Date object see http://www.w3schools.com/jsref/jsref_obj_date.asp
Note that w3schools is terribly outdated and normally you should not rely on it, but as far as I can see the function reference for the Date object is still correct

12. Fantastic, I'll do that now.
Just a quick Q - does what I need to put in supplement the current code, or replace any bits of it?

Cheers :-D

Alex

13. Assuming you're using the code from step 2 on the website you showed me:

Code:
```if (it's later than friday 17:00 AND earlier than sunday 23:59:59) {
display "It's the weekend"
} else {
var futuredate=new cdtime("countdowncontainer")
futuredate.displaycountdown("days", formatresults)
}```

14. I know I'm being REALLY thick here, but I simply don't get where to enter all this!

I've currently broken down "Step 1" and "Step 2" on the example into a HEAD.js file and a BODY.js file.
Their contents are:

Head.js
function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
var now=new Date();
var Y = now.getFullYear();
var m = now.getMonth();
var d = now.getDate();
var date = new Date();
while (date.getDay() != 5) {
date = new Date(Y,m,++d);
}
this.targetdate = new Date(Y,m,d,17,0,0);
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this

var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc

function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring=arguments[0]+" days, "+arguments[1]+" hours, and "+arguments[2]+" minutes left until the weekend"
}
else{ //else if target date/time met
var displaystring="The weekend is here!"
}
return displaystring
}

// JavaScript Document
and BODY.js
var futuredate=new cdtime("countdowncontainer")
futuredate.displaycountdown("days", formatresults)

var currentyear=new Date().getFullYear()
Now, do I have to put the "var d = new Date();
if (d.getDay() == 5 && d.getHours() > 17)" code you talked about in the head.js file, and then do a separate mod to the body.js file?

Aarrgghh. Sorry, I know this must be really irritating for you! Thanks for all your help though! :-)

Alex

15. Originally Posted by alexrob
Aarrgghh. Sorry, I know this must be really irritating for you! Thanks for all your help though! :-)
No worries. We're here to help
You want to put the code in your body.js

Code:
```var d = new Date();
if (d.getDay() == 5 && d.getHours() > 17 && it's earlier than sunday 23:59:59) {
document.getElementById("countdowncontainer").innerHTML = "It's the weekend";
} else {
var futuredate=new cdtime("countdowncontainer")
futuredate.displaycountdown("days", formatresults)
}```
I'll leave the it's earlier than sunday 23:59:59 part as an exercise to you

16. Originally Posted by ScallioXTX

I'll leave the it's earlier than sunday 23:59:59 part as an exercise to you
Aww, thanks :-)

Okies, so I've currently now got:

var d = new Date();
if (d.getDay() > 5 && d.getHours() == > 17 && d.getDay() == < 7 && d.getHours() == < 23 && d.getMinutes() == < 59) {
document.getElementById("countdowncontainer").innerHTML = "It's the weekend";
} else {
var futuredate=new cdtime("countdowncontainer")
futuredate.displaycountdown("days", formatresults)
}
...but dreamweaver is saying it's got a syntax error
Any clues? lol

Alex

17. Originally Posted by alexrob
...but dreamweaver is saying it's got a syntax error
Any clues? lol
You can use

== for "equals"
< for "is smaller than"
> for "is bigger than"
<= for "is smaller than, or equal to"
>= for "is bigger than, or equal to"

The "== >" and "== <" you used are indeed not valid.
I'll leave it to you to change the code using this post.
HINT: In a previous post I used the correct syntax ...

18. Here's another clue
;

(I presume JS does actually need it?)

19. Originally Posted by siteguru
Here's a clue
;

semi columns are optional in javascript, line breaks also work

20. I guess I'm just a creature of habit.

PS - it's semi-colon.

21. Off Topic:

Originally Posted by siteguru
PS - it's semi-colon.
Ah yes, I always have difficulty with the names of characters like that in English. Thank you for correcting me

22. Okies, thanks for this. I've now made the corrections - I see what went wrong :-)
Now, because it's Tuesday, I thought it would be fun to test and pretend the weekend goes from 17:00 on a Monday to 23:59 on a Tuesday. Unfortunately, the placement of that if statement isn't causing the timer to say "It's the weekend" today (Tuesday), it's just giving me a "6 days, 2hrs, etc, etc" read out.

I'll be honest, I'm really thankful for the help but this whole thing has me massively confused!

I've pasted the two files (both head.js and body.js) below. Head.js seems to look after the displaying of "It's the weekend", so the thing in body.js seems kinda pointless.

Head.js
function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
var now=new Date();
var Y = now.getFullYear();
var m = now.getMonth();
var d = now.getDate();
var date = new Date();
while (date.getDay() != 1) {
date = new Date(Y,m,++d);
}
this.targetdate = new Date(Y,m,d,17,0,0);
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this

var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc

function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring=arguments[0]+" days, "+arguments[1]+" hours, and "+arguments[2]+" minutes left until the weekend"
}
else{ //else if target date/time met
var displaystring="The weekend is here!"
}
return displaystring
}

// JavaScript Document
and body.js
var d = new Date();
if (d.getDay() > 1 && d.getHours() >= 17 && d.getDay() <= 2 && d.getHours() <= 23 && d.getMinutes() < 59) {
document.getElementById("countdowncontainer").innerHTML = "It's the weekend";
} else {
var futuredate=new cdtime("countdowncontainer")
futuredate.displaycountdown("days", formatresults)
}

23. Originally Posted by alexrob
I'll be honest, I'm really thankful for the help but this whole thing has me massively confused!
Understandable. One day you'll think back on this thread and laugh about it. Believe me, I've been there

As for the code, I should have been more clear. The first day time interval and the second time interval are actually seperate, so the IF statement doesn't make a whole lot of sense right now since everything is AND'ed together.

This should work
Code:
```var d = new Date();
if ((d.getDay() == 1 && d.getHours() >= 17) || (d.getDay() == 2 && d.getHours() <= 23 && d.getMinutes() < 59)) {
document.getElementById("countdowncontainer").innerHTML = "It's the weekend";
} else {
var futuredate=new cdtime("countdowncontainer")
futuredate.displaycountdown("days", formatresults)
}```
Basically what the IF statements now says is "IF (it's monday and it's later than 17:00:00) OR (it's tuesday and it's earlier than 23:59:59)", which is the same as "It is between monday 17:00:00 and tuesday 23:59:59". Think about it

PS. For completeness sake, if you'd want to do this for monday 17:00:00 until wednesday 23:59:59 you'd have to do it like so:
Code:
```var d = new Date();
if ((d.getDay() == 1 && d.getHours() >= 17) || d.getDay() == 2 || (d.getDay() == 3 && d.getHours() <= 23 && d.getMinutes() < 59)) {
document.getElementById("countdowncontainer").innerHTML = "It's the weekend";
} else {
var futuredate=new cdtime("countdowncontainer")
futuredate.displaycountdown("days", formatresults)
}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•