Creating a Groupon-Like Count Down Timer
Groupon is definitely one of the most rapid growth websites over past two years. As it spreads all over the world, a lot of Groupon clone sites have been built up. Despite how many different interface designs are there, the only element that is persistent across all of the clones' sites is the timer. As a developer, have you ever wonder how to build a countdown timer similar to Groupon's one?
In this tutorial, we will show you how to code a countdown timer using jQuery and PHP. Where jQuery will play the major part of the countdown function and we are just using PHP to output the time value. However you are free to use any language to insert the time value.
At the end of this tutorial, you will have a simple timer as shown below:
Create two php files called
index.php: this will be the front page to show the timer. And we will directly use PHP in this page to create a countdown start value.
- Get hour, minute and second Dom element using jQuery selector. This means when we use class, we will need to assign class 'hour' to hour element, 'min' to minute element and 'sec' to second element.
- Hold countdown time value using a variable.
- Countdown interval in millisecond. We want it to countdown per second. So set it to 1000 as 1000 millisecond equals 1 second.
- Hold ID value return by
setInterval(), and we will need to pass it to
setInterval()when countdown value is not zero.
setInterval()function and store ID value to timerInterval.
- Callback function
countdown()will be defined within Timer class to avoid conflict.
- Define callback function countdown.
- Stop calling countdown function by calling
clearInterval()when countdown hits 0.
- Calculate how many hours left.
- Calculate how many minutes left.
- Calculate how many seconds left.
- Prefix 0 to counter if needed.
Note: when using function
In this page, we will include jQuery from Google's CDN and include
timer.js which is defined above. And we will initiate the Timer object to do the countdown job. Lastly we will add some simple CSS style to it.
Copy and paste following code into
- Include jQuery and
- Defined a
DIVelement to hold the timer. Ensure you define
spanwith corresponding classes as discusssed in
- Initiate a Timer object when page is fully loaded. Take note how we create
timeLeftvalue using PHP, normally there should be some backend logic to calculate the countdown value.
- We use some very simple CSS style to style the page.