Reputation: 440
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?
Upvotes: 1
Views: 1416
Reputation: 363
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");
}
}
Upvotes: 1