W3Dhw1

by Leoooo

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://i.imgur.com/omX5Drl.png" style="position:absolute;top:0vw;left:0vw;width:70vw;z-index:-1">

</div>

JavaScript

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 = '10vw';
    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(89, 43%, 51%)";
    document.getElementsByTagName('body')[0].appendChild(this.element);
  }

	changeColor() {
  	// https://stackoverflow.com/questions/45147661/javascript-recursion-within-a-class/45147713
    var self = this;
  	var hue = Math.random()*200;
  	self.element.style.background = "hsl(" + hue + ", 43%, 51%)";  
    setTimeout (function() { self.changeColor() } , 1000);
		// setTimeout ( self.changeColor , 1000);  // why this is not working ...
  }

}

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

function init() {
  var light = new Light();
  light.changeColor();
}