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

230
Visualizações
How to toggle two elements correctly with two buttons?

I want to show cards when cards is clicked and show table when table is clicked. But by default, one of them needs to show at the beginning with the other hidden. But if either button is clicked on again the div will stay to what is clicked on. I have it half way working. If you start on the table button first you will see it working until you click again (same button) or start on the cards button. Any help is appreciated. Here is an example of what I need.

const targetTable = document.getElementById("table");
const targetCards = document.getElementById("cards");
const btn = document.getElementById("toggle");
const btn2 = document.getElementById("toggle2");


targetCards.style.display = "block";
targetTable.style.display = "none";

btn.onclick = function () {
  if (targetTable.style.display !== "none") {
    targetTable.style.display = "none";
  } else {
    targetTable.style.display = "block";
    targetCards.style.display = "none";
  }
};

btn2.onclick = function () {
  if (targetCards.style.display !== "none") {
    targetCards.style.display = "none";
  } else {
    targetCards.style.display = "block";
    targetTable.style.display = "none";
  }
};
<body>
  <div id="cards">This div shows cards.</div>
  <div id="table">This div shows table.</div>
  <button id="toggle">table</button>
  <button id="toggle2">cards</button>
</body>

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

0

Here's one way to approach it. Use classes to consolidate your functions, then use a data-attribute to designate which button reveals what item

document.querySelectorAll('.toggler').forEach(button => {
  button.addEventListener('click', e => {
    let targ = `#${e.target.dataset.ref}`;
    // set them all to hidden
    document.querySelectorAll('.toggles').forEach(div => div.classList.add('hide'));
    // reveal the one we want
    document.querySelector(targ).classList.remove('hide');
  });
});
.hide {
  display: none;
}
<div id="cards" class='toggles'>This div shows cards.</div>
<div id="table" class='toggles hide'>This div shows table.</div>
<button class='toggler' data-ref='table'>table</button>
<button class='toggler' data-ref='cards'>cards</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Little late, but i like js tasks :-)

const btns = document.querySelectorAll('.toggle');
const elem = document.querySelectorAll('.elem');

btns.forEach((b) => {  
  b.addEventListener('click', (e) => {    
    const t = e.target.getAttribute('data-type');    
    const classList = document.getElementById(t).classList;
    if (classList.length > 1) {
      elem.forEach((c) => {            
        c.classList.toggle('hidden')
      })      
    }
  });
});
.hidden {
  display: none;
}
<div>
  <div id="cards" class="elem ">This div shows cards.</div>
  <div id="table" class="elem hidden">This div shows table.</div>

  
  <button class="toggle" data-type="table">table</button>
  <button class="toggle" data-type="cards">cards</button>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understand your question correctly, you've overcomplicated it with the if statements. There's need to check what the current states are, you can just set them to what the buttons are supposed to do.
The functions can look like this:

btn.onclick = function () {
  targetCards.style.display = "none";
  targetTable.style.display = "block";
};

btn2.onclick = function () {
  targetTable.style.display = "none";
  targetCards.style.display = "block";
};

And here's the whole working snippet:

const targetTable = document.getElementById("table");
const targetCards = document.getElementById("cards");
const btn = document.getElementById("toggle");
const btn2 = document.getElementById("toggle2");


targetCards.style.display = "block";
targetTable.style.display = "none";

btn.onclick = function () {
  targetCards.style.display = "none";
  targetTable.style.display = "block";
};

btn2.onclick = function () {
  targetTable.style.display = "none";
  targetCards.style.display = "block";
};
<body>
  <div id="cards">This div shows cards.</div>
  <div id="table">This div shows table.</div>
  <button id="toggle">table</button>
  <button id="toggle2">cards</button>
</body>

You could also get a little bit fancy by having one button that toggles the display. It's not much more complicated.

const targetTable = document.getElementById("table");
const targetCards = document.getElementById("cards");
const btn = document.getElementById("toggle");

targetCards.style.display = "block";
targetTable.style.display = "none";

btn.onclick = function () {
  if (targetTable.style.display !== "none") {
    targetTable.style.display = "none";
    targetCards.style.display = "block";
    btn.innerHTML = "table";
  } else {
    targetTable.style.display = "block";
    targetCards.style.display = "none";
    btn.innerHTML = "cards";
  }
};
<body>
  <div id="cards">This div shows cards.</div>
  <div id="table">This div shows table.</div>
  <button id="toggle">table</button>
</body>

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