Traffic Light using JQuery

In this tutorial, I'll show you how to make traffic light using Jquery.

Click Here for DEMO

First thing, we need HTML to create the traffic light boxes. Here is the code:

HTML
<h2>Traffic Light</h2>
<div class="trafficlight">
   <ul class="box">
      <li class="red" id="red"></li>
      <li class="orange" id="orange"></li>
      <li class="green" id="green"></li>
   </ul>
   <ul class="smallbox">
      <li class="walk active" id="walk">WALK</li>
      <li class="stay" id="stay">STAY</li>
   </ul>
</div>

Then, we need CSS to style up the things. Here I use SCSS so I'll share you SCSS code.
SCSS
.trafficlight {
   width: 70px;
   margin: auto;
   position: relative;
   padding: 20px 0 100px;

   &:before{
      content: '';
      background: #000;
      width: 10px;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 50%;
      margin-left: -5px;
      border-radius: 10px 10px 0 0;
   }
}

.box,
.smallbox {
   @extend %listreset;
   width: 70px;
   background: black;
   border: 6px solid #999;
   text-align: center;
   padding: 5px 0;
   border-radius: 5px;
   position: relative;
   z-index: 1;
   text-align: center;
   font-weight: bold;
}

.box{
   margin: 0 0 30px;

   li{
      height: 30px;
      width: 30px;
      border-radius: 50%;
      display: inline-block;
      vertical-align: top;
      margin: 5px 0;
   }

   .red {
      background:red;
   }

   .orange {
      background:orange;
      opacity: 0.2;
   }

   .green {
      background:green;
      opacity: 0.2;
   }
}

.smallbox{
   .walk {
      color: green;
   }

   .stay {
      color: red;
      opacity: 0.2;
   }
}

Finally, we need Jquery Code to make traffic lights. So, here's the Jquery below.
Jquery
// traffic light
function green() {
 $('#red').css('opacity', 0.2);
 $('#orange').css('opacity', 0.2);
 $('#green').css('opacity', 1);
}
function orange() {
 $('#green').css('opacity', 0.2);
 $('#orange').css('opacity', 1);
 clearInterval(greenlight);
}
function red() {
 $('#orange').css('opacity', 0.2);
 $('#red').css('opacity', 1);
 clearInterval(orangelight);
 greenlight = setInterval(green, 5000);
 orangelight = setInterval(orange, 15000);
}
var greenlight = setInterval(green, 5000);
var orangelight = setInterval(orange, 15000);
var redlight = setInterval(red, 17000);

// traffic words
function stay() {
 $('#walk').css('opacity', 0.2);
 $('#stay').css('opacity', 1);
}
function walk() {
 $('#stay').css('opacity', 0.2);
 $('#walk').css('opacity', 1);
 clearInterval(peoplestay);
 peoplestay = setInterval(stay, 5000);
}
var peoplestay = setInterval(stay, 5000);
var peoplewalk = setInterval(walk, 17000);

I hope this is working well. If you have any thought or any new sharing, feel free to comment below.

Cheers!!

Share this

Related Posts