Ad

Use Multiple Tabs Component On The Same Page

- 1 answer

i'm trying to achieve a functionality for tabs and i'm stuck on something. i want to use the same function for multiple tabs but without interfere one with another if i have multiple tabs component in the same page. do you have any ideas on how i can achieve that? many thanks. until now i just manage to avoid the inline javascript from the W3schools example but it's only working for one component.

<div class="first-tab-component>
 <div class="tab">
  <button class="tablinks" data-id="1">London</button>
  <button class="tablinks" data-id="2">Paris</button>
  <button class="tablinks" data-id="3">Tokyo</button>
</div>

<div data-id="1" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div data-id="2" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div data-id="3" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>
</div>

<div class="second-tab-component>
 <div class="tab">
  <button class="tablinks" data-id="1">London</button>
  <button class="tablinks" data-id="2">Paris</button>
  <button class="tablinks" data-id="3">Tokyo</button>
</div>

<div data-id="1" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div data-id="2" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div data-id="3" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>
</div>


let handleClick = e => {
  Array.from(document.querySelectorAll(".active"), e => e.classList.remove("active")); // remove `active` class from every elements which contains him.
  e.target.classList.add("active");
  document.querySelector(`div.tabcontent[data-id*="${e.target.dataset.id}"]`).classList.add("active");
};

Array.from(document.getElementsByClassName("tablinks"), btn => btn.addEventListener('click', handleClick, false));

here i have the example https://jsfiddle.net/xn3yd852/

Ad

Answer

You can replace:

Array.from(document.querySelectorAll(".active"), e => e.classList.remove("active")); // remove `active` class from every elements which contains him.

with

Array.from(e.target.parentElement.parentElement.querySelectorAll(".active"), e => e.classList.remove("active")) 

This will only remove the .active class from its parent tab component

https://jsfiddle.net/Buntel/2rmuk03c/6/

Ad
source: stackoverflow.com
Ad