I want every time I click on the 'Armchair' function it changes color

4
function Selecionar(){
    var selecionado = document.getElementById("poltronas");
    selecionado.style.background = "yellow";

    var selecionado = document.getElementById("poltronas");
    selecionado.style.background = "green";
}

<a href="#" onclick="Selecionar()"><div id="poltronas">1</div></a>
    
asked by anonymous 14.05.2018 / 04:02

2 answers

1

A simple way is to check the current color and change based on it. The code is close to your current one:

function Selecionar(){
    var selecionado = document.getElementById("poltronas");

    // Se estiver amarelo, troca pra verde
    if(selecionado.style.background === "yellow") {
        selecionado.style.background = "green";

    // Senão, troca pra amarelo
    } else {
        selecionado.style.background = "yellow";
    }
}

This will work if the initial color is set to yellow, by JS or inline style:

<div id="poltronas" style="background: yellow"></div>

Without this the initial color would be undefined from the point of view of this script, and the first click would define yellow. From there it would function normally.

    
14.05.2018 / 04:14
1

If you have more than two colors, you can use an array to store the values and then change according to the amount of click.

Commented example:

/* Define as cores */
const cores = ["yellow", "green", "red", "orange"]

/* Define a posição da cor atual */
let corIndex = 0;

/* Elemento que irá sofrer as alterações */
const poltrona = document.getElementById("poltronas");

function Selecionar(){
  /**
   * Verifica se é uma cor válida
   * Caso não seja, atribui o índice 0
   */
  if (!cores[corIndex]) {
    corIndex = 0
  }
  
  /* Altera a cor e muda o índice para a próxima */
  poltrona.style.setProperty("background", cores[corIndex++])
}
#poltronas {
  height: 100px;
  width: 100px
}
<a href="#" onclick="Selecionar()">Mudar de cor</a>

<div id="poltronas"></div>
    
14.05.2018 / 04:21