Arman
Arman

Reputation: 1

How to make independent toggle buttons?

So that everyone opens their own content. Making an individual identifier is a bad idea, there are 1000 such buttons

  <button onclick="showHide()" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">1</h1>


  <button onclick="showHide()" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">2</h1>


  <button onclick="showHide()" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">3</h1>


<style>
  .hide{
    display:none;
  }
</style>
let userSection = document.querySelector(".toggle__elements");
let isShow = true

function showHide(){
  isShow=!isShow
  userSection.classList.toggle("hide", isShow);
}

Upvotes: 0

Views: 242

Answers (2)

Lu&#239;s
Lu&#239;s

Reputation: 2843

I've updated your function to work independently for each button. The comments inside the snippet should provide some information on how this is achieved. The most notable thing here is that we can use this in onclick="showHide(this)" to pass down the instance of our button element to the showHide function. Which allows us to select the correct sibling element and toggle its hide class.

function showHide(button){
  const userSection = button.nextSibling.nextElementSibling; // Select the next sibling of the clicked button
  userSection.classList.toggle("hide");
}
<button onclick="showHide(this)" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">1</h1>


  <button onclick="showHide(this)" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">2</h1>


  <button onclick="showHide(this)" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">3</h1>


<style>
  .hide{
    display:none;
  }
</style>

Upvotes: 1

Diego D
Diego D

Reputation: 8148

You should use window.event, from inside the event handler, to grab the event fired and fetch its target property to get the element firing the event.

Once you have the button that got clicked, you can use a strategy like getting its next sibling like I did here on this demo, and toggle the hide class.

function showHide(){
  const elementClicked = window.event.target;  
  const elementNextToClickedOne = elementClicked.nextElementSibling;    
  elementNextToClickedOne.classList.toggle("hide");
}
.toggle__button{
  cursor: pointer;
}  
  
.hide{
  display:none;
}
  <button onclick="showHide()" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">1</h1>


  <button onclick="showHide()" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">2</h1>


  <button onclick="showHide()" class="toggle__button">click</button>
  <h1 class="toggle__elements hide">3</h1>

Upvotes: 3

Related Questions