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

145
Visualizações
Show/hide between two elements randomly onload

I have two elements, .a and .b. By default, both elements have display: none. I want to make one of the two appear randomly when the page loads. Sometimes .a appears, sometimes .b appears, by giving the class .c which will provide display: block.

This is what I have tried but failed because sometimes both are shown and hidden together:

window.addEventListener('load', function() {
  var scenario = Math.random() < .5 ? "c" : "d";

  document.querySelector(".a").classList.add(scenario);
  document.querySelector(".b").classList.add(scenario);

});
.a, .b {display:none}
.a.c, .b.c {display:block}
<div class='a'>aaa</div>
<div class='b'>bbb</div>

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

0

Your code doesn't work because you calculate the scenario randomly, but then apply it to both elements.

To do what you require use the Math.random logic to determine which element ot target, either .a or .b, then add the c class to that element only. Try this:

window.addEventListener('load', function() {
  var selector = Math.random() < .5 ? ".a" : ".b";
  document.querySelector(selector).classList.add('c');
});
.a, .b { display: none; }
.a.c, .b.c { display: block; }
<div class="a">aaa</div>
<div class="b">bbb</div>

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