JSFiddle - React, Tailwind, and code Playground

by CommandLineDesign

HTML

<div class="trafficLight" id="myLight">
  <div class="light red">
  
  </div>
  <div class="light yellow">
  
  </div>
  <div class="light green">
  
  </div>
</div>

CSS

div.trafficLight {
  width: 50px;
  background: grey;
  border: 1px solid black;
}

.light {
  opacity: 0.25;
  width: 40px;
  height: 40px;
  background: grey;
  border: 1px solid black;
}

.light.on {
  opacity: 1;
}

.red{
  background-color: red;
}

.yellow{
  background-color: yellow;
}

.green{
  background-color: green;
}

JavaScript

let TrafficLight = function(elementId){

	this.lights = ['red', 'yellow', 'green']
  
  this.states = []
  
  let context = this
  
  for(let color of this.lights) {
  console.log(color)
  	this.states.push(new Light(color, context))
  }
  
  this.states[0].toggle()
  
  this.currentState = 0
  
  this.changeStates = function() {
  	let toggleThis = false
  	for(let i in this.states) {
      if(toggleThis){
				this.states[i].toggle()
      }
    	if(this.states[i].state == 'on'){
      	this.states[i].toggle()
      	toggleThis = true
        if(i == this.states.length){
        	this.states[0].toggle()
        }
      }
    }
  }

}

let Light = function(color, context){
	
  this.state = 'off';
  this.color = color;
  
  let thisElement = document.getElementsByClassName(color)
  
 this.toggle = function(){
 	if(this.state === 'on'){
  	this.state = 'off'
 		thisElement[0].classList.remove('on')
  } else {
  	this.state = 'on'
   	thisElement[0].classList.add('on') 
  }
  console.log(thisElement[0])
  
 }
 
 

 thisElement[0].addEventListener('click', function() {
 	context.changeStates()
 })
 
}

let myLight = new TrafficLight('myLight')