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

Asked

Viewed 57 times

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>
  • Random or preset colors?

  • green and yellow presets, when not in one color have to be in the other

2 answers

1

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

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 work normally.

  • It worked perfectly, thank you very much

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>

  • it will help me a lot from now on, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.