JSFiddle - React, Tailwind, and code Playground

by RGMGx

HTML

<div>
  <!--
  <div id="light" style="position:absolute;top:10vw;left:30vw;  
background:pink;width:20px;height:20px;  
border-radius:15px;z-index:1"></div>
-->
  <img src="https://rgmgx.github.io/3W3D/xmastree.jpg" style="position:absolute;top:0vw;left:0vw;width:100vw;z-index:-1">

</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

<p id='status'></p>
<button id="toggle">
Turn OFF
</button>

JavaScript

var status = 1;

var turn = 0

class Light {

  constructor() {
    // create/append div dynamically
    // https://stackoverflow.com/questions/14004117/create-div-and-append-div-dynamically
    this.element = document.createElement('div');
    //this = iDiv;
    this.element.id = 'light';
    // set element style attribute
    //https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
    this.element.style.cssText = "position:absolute;width:20px;height:20px;border-radius:15px;z-index:1";
    this.element.style.top = '30vw';
    this.element.style.left = '30vw';
    // CSS color property: https://www.w3schools.com/cssref/pr_text_color.asp
    // hsl: https://www.w3schools.com/colors/colors_hsl.asp
    this.element.style.background = "hsl(100, 100%, 30%)";
    document.getElementsByTagName('body')[0].appendChild(this.element);
  }

  changeColor() {
    // https://stackoverflow.com/questions/45147661/javascript-recursion-within-a-class/45147713

    // setTimeout ( self.changeColor , 1000);  // why this is not working ...
    var self = this;
    var hue = Math.random() * 200;
    /*
 
    }*/
    if (turn == 0) {
      self.element.style.background = "hsl(" + hue + ", 80%, 50%)";
      setTimeout(function() {
        self.changeColor()
      }, 500);
      console.log("555")
    }
  }
  off() {
    var self = this;
    if (turn == 1) {
      self.element.style.background = "hsl( 50, 0%, 50%)";
      setTimeout(function() {
        self.off()
      }, 500);
      console.log("444")
    }
  }

}

////////////////////////////////
init();


function init() {
  var light = new Light();
  light.element.style.top = '30vw';
  light.element.style.left = '54vw';
  // light.changeColor();
  var light2 = new Light();
  light2.element.style.top = '24vw';
  light2.element.style.left = '38vw';
  // light2.changeColor();
  var light3 = new Light();
  light3.element.style.top = '50vw';
  light3.element.style.left = '60vw';
  // light3.changeColor();
  var light4 = new...