Home > Enterprise >  How to change a color of element on click from a set of colors
How to change a color of element on click from a set of colors

Time:06-16

Lets suppose I have a rectangular div called sun.

I have 4 colors for the div.

The colors are red, green, blue and yellow respectively.

The initial color is red.

What I want is when user clicks on the rectangle, the color of rectangle should change from red to green. When clicked again, green to blue, and thus on another click, blue to yellow and atlast when user clicks again the color should change from yellow to red and the cycle should continue. I can not implement such algorithm.

Answer is appreciated if if-else tree is used (although not necessary).

CodePudding user response:

Like @Bravo comment you can use javascript array and add with eventListener

It rought but that it.

const box = document.querySelector('.box');

const listColor = ['red', 'green', 'blue', 'yellow'];

let currentColor = 1;
box.addEventListener('click', function() {
  this.style.backgroundColor = listColor[currentColor  ];
  if (currentColor == listColor.length) {
    currentColor = 0;
  }
})
.box {
  width: 100px;
  height: 100px;
  background-color: red;
  transition: all .3s ease;
}
<div ></div>

CodePudding user response:

If the other answers don't help, here's what I was suggesting in the comment

a simple array and an index into the array that is "wrapped" to 0 using the modulo operator

document.querySelector(".tgt").addEventListener(
    "click", 
    ((colours, index) => 
        e => e.target.style.backgroundColor = colours[(index = (index   1) % colours.length)]
    )(["red", "green", "blue", "yellow"], 0)
);
<div  style="background-color:red;height:64px;aspect-ratio:16/9">
</div>

Added benefit - NO global variables required

CodePudding user response:

your problem have simple solution with js arrays and index check

// DOM Element 
const SUN = document.getElementById("sun");

// Variables
let index = 0;

// Colors 
const COLORS = ["red", "green", "blue", "yellow"];

// Handler
const initColor = () => {
  SUN.style.backgroundColor = COLORS[index];
}

const changeColor = () => {
  index  ;
  if (COLORS[index]) {
    SUN.style.backgroundColor = COLORS[index];
  }
}

// Event Listeners 
window.addEventListener("DOMContentLoaded", initColor);

SUN.addEventListener("click", changeColor)
#sun {
  width: 400px;
  cursor: pointer;
  height: 200px;
  border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./style.css">
</head>

<body>
</body>
<div id="sun">

</div>
<script src="./script.js"></script>

</html>

  • Related