0

I am having trouble with my javascript can anyone help me figure out what I am doing wrong? I am trying to add an active class to my navbar tabs, I just started using php and I have had a lot of trouble with this.

<script>
function activePage(evt) {

    var url = window.location.href;     
    var splitUrl = url.split('/');
    var output = splitUrl[splitUrl.length - 1];
    console.log(output);
    console.log(splitUrl);
    console.log(url);

    if (output === 'index.html') {
        evt.currentTarget.className += " active";
    }

    if (output === 'page1.html') {
        evt.currentTarget.className += " active";
    }

    if (output === 'page2.html') {
        evt.currentTarget.className += " active";
    }

    if (output === 'page3.html') {
        evt.currentTarget.className += " active";
    }
}

window.onload = function () {
    activePage(null, null);
};

<div class="navbar">
  <div class="nav-tab"><a href="#" class="logo">logo</a></div>
  <div class="filler"></div>
  <div class="nav-tab"><a href="index.php" onclick="activePage(event)" class="page">Home</a></div>
  <div class="nav-tab"><a href="page1.php" onclick="activePage(event)" class="page">page1</a></div>
  <div class="nav-tab"><a href="page2.php" onclick="activePage(event)" class="page">page2</a></div>
<div class="nav-tab"><a href="page3.php" onclick="activePage(event)" class="page">page3</a></div>

  • You need to make sure to also remove the "active" class if you're no longer on that route. I see that you're just appending it. – Tony Tai Nguyen Oct 03 '17 at 22:48
  • JS elements have a [`.classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) property which makes adding and removing classes easy! – ContinuousLoad Oct 03 '17 at 23:07

1 Answers1

0

From this answer, and as the comments said, use classList methods.

if (output === 'index.html') {
    evt.currentTarget.classList.add(" active");
}
Jason
  • 514
  • 5
  • 21