Skip to content
Advertisement

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>

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement