user3247204
user3247204

Reputation: 11

On click set active tab into the middle of tabs using javascript or css

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.

Upvotes: 0

Views: 428

Answers (1)

vanowm
vanowm

Reputation: 10201

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>

Upvotes: 0

Related Questions