简体   繁体   中英

Active Navigation Menu Highlight for Current Page from a Single Header File

How can I make the navigation menu get highlighted for the current page that I am visiting?

header.php

<div class="header-menu">
  <div class="nav">
    <ul>
      <a href="index.php"><li>Home</li></a>
      <a href=""><li>Register</li></a>
      <a href="login.php"><li>Login</li></a>
      <a href=""><li>FAQ</li></a>
      <a href=""><li>Advertise</li></a>
      <a href=""><li>Terms</li></a>
      <a href=""><li>Support</li></a>
      <a href=""><li>Forum</li></a>
    </ul>
  </div>
</div>

If I am currently on the login.php page, then in the navigation menu the login item should be highlighted (like bg color change). I can do this in PHP using conditional logic to set an active class by setting a variable on each page which identifies the current page.

For example something like if($page == 2){ echo "active" }

But, I want to achieve this using CSS. I have googled this and found ways of adding active class on "each" page which is very simple but the problem is I have my navigation menu on a single header file where that method requires to have menu on all the pages separately.

How can I achieve this using CSS, or Javascript / jQuery if it is not possible using CSS?

You can achieve this with pure JavaScript and HTML.

<a href="index.php" class="myLink" data-pathname="/index.php"><li>Home</li></a>
<a href="forum.php" class="myLink" data-pathname="/forum.php"><li>Forum</li></a>

If needed active class in <li> instead of anchor tag <a>

<a href="index.php"><li class="myLink" data-pathname="/index.php">Home</li></a>
<a href="forum.php"><li class="myLink" data-pathname="/forum.php">Forum</li></a>
var links = document.getElementsByClassName("myLink");
var URL = window.location.pathname;
URL = URL.substring(URL.lastIndexOf('/'));
for (var i = 0; i < links.length; i++) {
  if (links[i].dataset.pathname == URL) {
    links[i].classList.add("active");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM