I would like to create a countdown clock that when you show up on the page it starts to countdown from a pre-defined number, say 8 hours. If you leave the page, say after 2 hours, I would like it to stop counting down. If you return to the page I want it to resume counting down, now with only 6 hours left.
Is this possible using javascript client side, and php server side?
If I wanted to create multiple user generated countdowns can I use mySQL to store the different variables?
Obviously I have a lot to work out here, I don’t want someone to write me the whole code. I am looking for a starting point, maybe some tutorials or advice on which way to start perusing. I am very much a novice at js, php, mysql but can work with them.
Here’s a solution that uses a countdown plugin for jQuery. Download the jQuery Countdown plugin, and place
jquery.countdown.cssandjquery.countdown.min.jsin the same folder as your file (or elsewhere, and adjust the paths in the code below). In the head section of your document include this:Somewhere in the PHP code, before anything is outputted, run this to set when the time will be:
Then, where you want the timestamp to appear, output this HTML:
And somewhere after it, output this JavaScript:
EDIT: Alright, here are some improvement on my previous answer to include pausing when the user leaves the page. I’m also switching the post over to community wiki so anyone is welcome to edit and improve it.
In order to track when the user was last on the page, you need to keep a cookie that you update every 5 seconds or so with the current time. Here’s a bit of JavaScript that does just that:
You need to run
updateCookie()once and then it will keep running every five seconds. To have it run for the first time as soon as the page has finished on loading, add an onLoad to your body tag, like this:Your PHP code will then look like this instead of the one above:
All the cookies are set to expire after 30 days, so if your user stays away for more than 30 days they will reset.