Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda