0

I am using tabs and I want to show active tab in the middle of the tabs using pure javascript without using document.

Tabs listing:

.tablist li:nth-of-type(1) { order: 3; }
.tablist li:nth-of-type(2) { order: 2; }
.tablist li:nth-of-type(3) { order: 5; }
.tablist li:nth-of-type(4) { order: 4; }
.tablist li:nth-of-type(5) { order: 1; }
.tablist li.tabs.tab-active{ order: 3 !important }
<ul class="tablist">
<li class="tabs">Marketing</li>
<li class="tabs">Manufacturing</li>
<li class="tabs tab-active" >Municipalities</li>
<li class="tabs">Retail</li>
<li class="tabs">Healthcare</li>
</ul>

I have tried but it only helps with first 3 tabs but not with last 2 tabs last two tabs switch on last positions only.

I am trying to use this functionality in Frontity so it doesn't support document.

I have only tried css not found any solution using javascript.

Please help me out for this issue.

Kas Elvirov
  • 7,394
  • 4
  • 40
  • 62

1 Answers1

0

Here is a javascript version, basically it loops through the list of tabs and update their order when a tab clicked.

const tablist = document.querySelector(".tablist"),
      tabs = Array.from( tablist.querySelectorAll(".tabs")).sort((a,b) => getComputedStyle(a).order - getComputedStyle(b).order); //get proper initial order

tablist.addEventListener("click", e =>
{
  if (!e.target.matches(".tabs"))
    return;

  for(let i = 0, order = 0, half = Math.round(tabs.length / 2); i < tabs.length; i++)
  {
    tabs[i].classList.toggle("tab-active", tabs[i] === e.target);
    tabs[i].style.order = (tabs[i] === e.target ? half : ++order == half ? ++order : order);
  }
});

tablist.querySelector(".tab-active")?.click(); //initialize order
.tablist li:nth-of-type(1) { order: 3; }
.tablist li:nth-of-type(2) { order: 2; }
.tablist li:nth-of-type(3) { order: 5; }
.tablist li:nth-of-type(4) { order: 4; }
.tablist li:nth-of-type(5) { order: 1; }

.tablist { display: grid; }
.tablist li.tab-active { font-weight: bold; }
.tabs { cursor: pointer; user-select: none; }
<ul class="tablist">
  <li class="tabs">Marketing</li>
  <li class="tabs">Manufacturing</li>
  <li class="tabs">Retail</li>
  <li class="tabs tab-active">Municipalities</li>
  <li class="tabs">Healthcare</li>
</ul>
vanowm
  • 9,466
  • 2
  • 21
  • 37
  • How to use **document.querySelector(".tablist")** in reactjs. As I said I am using frontity a react js framework which does not support document selection. – user3247204 Apr 10 '22 at 09:59
  • Thanks a lot I have successfully implemented it and its functional now. – user3247204 Apr 10 '22 at 12:55
  • hi, there is a change in order please help me. selected index will be on position 3 but the rest of the tabs' order will be changed if selected 4th one then order will be `2 3 4 5 1` from `1 2 3 4 5` and so on. – user3247204 Apr 15 '22 at 21:57
  • This cycle will be anti clock wise – user3247204 Apr 15 '22 at 22:01