17 Nov 2013

How to make a super simple countdown using pure javascript



Hi friends . In this tutorial  we will be making a super simple countdown using raw JavaScript and some Lil bit of CSS and HTML to add  to the UI.

This will be a very easy tutorial , so i will not be using a libraries like jquery or advanced features like getting the users time etc.


Demo

Lets begin by creating an a basic HTML file.


  <! doctype html>
<head>
 <title> hello</title>
 <link href ="style.css" type = "text/css" rel ="stylesheet"/>
</head>
<body>
   
</body>
</html>

Now insert a  div in the body. 

<div id = "cont"> </div>

We will be using this div as a  target to the javscript DOM.

Now add this javscript below the  the div tag . Dont worry about the code I'll explain it.

<script type="text/javascript">
    var b =100;
      var t = setInterval(function() {
        var a = document.getElementById("bt1");
          a.innerHTML =b;
          b--
          if(b%2==0){
              a.style.background = 'red';
              a.style.borderRadius= 20+"px";
            }
            else{
             
              a.style.background = 'yellow';
              a.style.borderRadius= 20+"px";
            }
          if (b == 0){
            clearInterval(t);
           
          return b;
          }
       },200);
    </script>

Ok that's all you need to make the countdown work; But I'm just going to add some basic CSS to make it look better. Insert the following css code
*{
 margin:0px;
 padding:0px;
}


.button{
    text-decoration: none;
    font-size: 30px;
    font-family: impact;
    margin:0px auto;
    background:#99defd;
    border: 2px solid black;
    border-radius: 0px;
}

.button  a:hover{
    background: yellow;
}


That's it ! now i'll explain the what happens inside the code block.
Firstly we use a variable called b to set the intial value of the countdown to 100 so that it will count back from 100-0.

 Next we use a setinterval function and target the element so each time within an interval of 200 microseconds the div will change it's innerHTML value.

 I used an if condition to change the div's css at very even intervals .Lastly  i added a clearInterval   function  to clear the timer when the value changes to 0.

3 comments:

  1. Thanks! pls make a tutorial on how to do some action based on time.

    ReplyDelete
  2. Dude nice topic although i'm not much into css.

    ReplyDelete