Posts | Comments | Email

Making a swoopo style count down timer with jQuery

Today we will be using jQuery to make a swoopo style countdown timer clone. Out timer will count down from a set amount, but when an element is clicked, more time will be added to the timer. Let’s begin.

Frist, out html:

    <div class="countdown"></div>
    <span class="add">click</span>

We have created to a div with the class “countdown” which will hold our swoopo style count down timer. Next we have the word click wrapped in span tags with the class “add”. This is what we will click on to add time to our timer. Simple enough. Now for our jQuery:

          var count = 100;
          countdown = setInterval(function(){
            $(".countdown").html(count + " seconds remaining");
            if (count == 0) {
                alert('game over');
          }, 1000);
              count = count + 10;

We start with our normal jQuery ready block. We then set our count variable which is the amount of time in seconds that the timer will count down. We then use jQuery’s setInterval function which we set to run every 1 second (1000 milliseconds). The sytax for this without any other script is like so:

    countdown = setInterval(function(){}, 1000);

Inside our setInterval function we firstly replace the html inside the div with a class “countdown” with the coun variable and the message “seconds remaining”. We then check if the count variable equals 0, in which case we alert the message “game over”. We then decrease the count by 1 (count–).

Next we have a simple jQuery click function on the element with the class “add” which adds 10 to the count.
There we have it, swoopo. Almost.

You can check out the incredibly exciting demo here and download the source here.


Comments are closed.