0

I'm trying to add an "active" class (i.e. class="active") to the appropriate menu list item based upon the page it is on once the page loads.
Below is my menu(for mobile and desktop) as it stands right now. I've tried every snippet of code I could find in this regard and nothing works.
So, can someone please explain simply where and how to add in javascript to define this task?

nav ul li.active a:after {
  content: '';
  background: url("../img/header-active.png") no-repeat;
  width: 14px;
  height: 7px;
  top: 24px;
  right: 0px;
  left: 0px;
  margin: 0 auto;
  position: absolute;
  display: block;
}
<!-- Main menu -->
<nav class="desktop">
  <ul>
    <li><a href="/">home</a></li>
    <li class="active"><a href="our-authors.html">our authors</a></li>
    <li><a href="our-books.html">our books</a></li>
    <li><a href="publish-with-us.html">publish with us</a></li>
    <li><a href="careers.html">careers</a></li>
    <li><a href="contact.html">contact</a></li>
  </ul>
</nav>
<!-- Main menu -->
<!-- Mobile menu -->
<div id="mobile-menu" class="mobile">
  <div class="mob-menu" onclick="menuChange(this)">
    <div class="bar1"></div>
    <div class="bar2"></div>
    <div class="bar3"></div>
  </div>
  <ul>
    <li><a href="/">home</a></li>
    <li class="active"><a href="our-authors.html">our authors</a></li>
    <li><a href="our-books.html">our books</a></li>
    <li><a href="publish-with-us.html">publish with us</a></li>
    <li><a href="careers.html">careers</a></li>
    <li><a href="contact.html">contact</a></li>
    <li><a href="bestseller_engine.html">The TreeShade Bestseller Engine</a></li>
  </ul>
</div>
<!-- Mobile menu -->
Code_Ninja
  • 1,729
  • 1
  • 14
  • 38

1 Answers1

0

Use location.pathname.

var path = location.pathname.replace("/", "");
var anchor = document.querySelector("a[href='" + path + "']");

anchor.parentNode.classList.add("active")

I don't know why you want to do it like this, it's best to do it in the server dynamically

Jeeva
  • 3,975
  • 3
  • 23
  • 47