Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
How to change a color of element on click from a set of colors

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).

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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 class="box"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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 class="tgt" style="background-color:red;height:64px;aspect-ratio:16/9">
</div>

Added benefit - NO global variables required

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda