|

Make a simple countdown timer in jQuery

Need to make a countdown timer for your website? I will show you how to do this easily on jQuery.

First, we need some HTML to hold our number.

<div class="container">
  <span class="number">60</span> <!-- We set this number to the number we will start our counter -->
</div>

The next thing that I will do is add a small amount of CSS (the Sassy way) to move my countdown to the center of the page and make the text larger.

.container {
  margin: 48px auto;
  width: 200px;
  .number {
    font-size: 120px;
  }
}

Finally, some jQuery to make the countdown actually, well… count down.

var num = 60; // This is the starting number. We will decrement this every second until we reach 0
var holder = $('.number'); // Make my .number class a variable

function countDown(){ // Create a function that we can call later
  if(num > 0){ // We need to check to make sure our countdown stops once it gets to 0
    num = num - 1; // Decrement our num variable
    holder.text(num); // Replace the text in our .number span with the freshly decremented num variable
  }
}

setInterval(countDown, 1000); // Use the setInterval method to call our countDown function every second. The 1000 is milliseconds, which equals 1 second

Pretty simple, huh? Basically, we set a variable to the number we want to start counting down from, and then we decrement that number every second with setInterval. As soon as we decrement the number, we update the text inside our span to reflect the newly decremented number.

For a live example, check out this Pen at Codepen.io

Leave a Reply

Your email address will not be published. Required fields are marked *