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

201
Visualizações
Js background color changer

Each square has a random color. For example, pink becomes green, orange becomes pink etc.How can I change the backgrounds?

<section>
    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>
    <div id="four"></div>
    <button id="btn">Click Me</button>
</section>




  let colors = ["pink" , 'yellow' , 'green' , 'blue']
let btn = document.getElementById('btn')
let one = document.getElementById('one')
let two = document.getElementById('two')
let three = document.getElementById('three')
let four = document.getElementById('four')

one.style.backgroundColor = colors[0]
two.style.backgroundColor = colors[1]
three.style.backgroundColor = colors[2]
four.style.backgroundColor = colors[3]

btn.addEventListener('click' , function(){
    let randomColor = colors[Math.floor(Math.random() * colors.length)]

    one.style.backgroundColor = randomColor

})

and then i cant understand what to do

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try this one instead which is easier by using forEach loop.

Use unshift to move the last element to the top of the array every time user clicks it.

let colors = ["pink" , 'yellow' , 'green' , 'blue']
//Assign orginial color:
document.querySelectorAll('div').forEach((item,index)=>{
item.style.backgroundColor = colors[index]
})
document.querySelector('#btn').addEventListener("click",function(){
document.querySelectorAll('div').forEach((item,index)=>{
item.style.backgroundColor = colors[index]
})
colors.unshift(colors.splice(colors.length-1, 1)[0]);
})
<div id="one">1</div>
    <div id="two">2</div>
    <div id="three">3</div>
    <div id="four">4</div>
    <button id="btn">Click Me</button>

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