Home > Software design >  Active tab in nav bar
Active tab in nav bar

Time:12-19

I'm trying to create an active tab in my nav bar. I have used javascript for this. I have the javascript in my code. I can't find the reason why it isn't working

var btnContainer = document.getElementById("active-link");
var btns = btnContainer.getElementsByClassName("button");

for (var i = 0; i < btns.length; i  ) {
  btns[i].addEventListener('click', function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace("active");
    this.className  = "active";
  })
}
.active-link {
  display: flex;
  list-style: none;
  position: relative;
  top: 10rem;
  left: 25%;
  margin: 100px -5px;
}

.button {
  text-decoration: none;
  padding-right: 100px;
  padding-left: 100px;
  padding-bottom: 10px;
  cursor: pointer;
  display: inline-block;
  border: none;
  background-color: transparent;
  color: rgb(0, 0, 0);
  border-bottom: 2px solid black;
  font-size: 1.5rem;
  transition: ease;
}

.button:hover {
  color: red;
  border-bottom: 5px solid red;
  padding-bottom: 7px;
}
<div  id="active-link">
  <li>
    <a >him</a>
  </li>
  <li>
    <a >her</a>
  </li>
  <li>
    <a >xyz</a>
  </li>

</div>

active links that are padded. Reference can be something like the active tabs in new balances website

CodePudding user response:

@Vadar

I have added the new function for removing class from all current active tabs. It will be active one tab at a time.

Here is the solution:

var btnContainer = document.getElementById("active-link");
var btns = btnContainer.getElementsByClassName("button");


function removeClass(elems, className) {
  [].forEach.call(document.querySelectorAll(elems), function(el) {
    el.classList.remove(className);
  });
}

for (var i = 0; i < btns.length; i  ) {
  btns[i].addEventListener('click', function(e) {
    removeClass('.button', 'active')
    this.classList.toggle('active');
  })
}
.active-link {
  display: flex;
  list-style: none;
  position: relative;
  top: 10rem;
  left: 25%;
  margin: 100px -5px;
}

.button {
  text-decoration: none;
  padding-right: 100px;
  padding-left: 100px;
  padding-bottom: 10px;
  cursor: pointer;
  display: inline-block;
  border: none;
  background-color: transparent;
  color: rgb(0, 0, 0);
  border-bottom: 2px solid black;
  font-size: 1.5rem;
  transition: ease;
}

.button:hover,
.active {
  color: red;
  border-bottom: 5px solid red;
  padding-bottom: 7px;
}
<div  id="active-link">
  <li>
    <a >him</a>
  </li>
  <li>
    <a >her</a>
  </li>
  <li>
    <a >xyz</a>
  </li>

</div>

CodePudding user response:

It is because nothing is active by default. Try adding an active element other wise the code :

 var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace("active");

Will give an error.

Also, do check your JS console to find the error and figure out on your own :)

  • Related