Hi I am trying to create a portfolio website. In order to not have to recreate the header for each page, I decided do add it using the PHP include
function. My only problem now is when I click a link to navigate to another page the active link isn't changing respectively.
The included HTML
<ul id="main-menu">
<li><a href="index.php" class="active">home</a></li>
<li><a href="about.php">about us</a></li>
<li><a href="portfolio.php">portfolio</a></li>
<li><a href="contact.php">contact</a></li>
</ul>
Javascript:
$(document).ready(function(){
var $menu = $("ul#main-menu li a");
$menu.click(function(){
$menu.each(function(){
$(this).removeClass("active");
});
$(this).addClass("active");
});
});
I know that the problem is that each time the page loads - it resets the class active to the first link. What I don't know is: how to dynamically add the active class to the page-matching link?
You need this:
$(document).ready(function(){
var i = document.location.href.lastIndexOf("/");
var currentPHP = document.location.href.substr(i+1);
$("ul#main-menu li a").removeClass('active');
$("ul#main-menu li a[href^='"+currentPHP+"']").addClass('active');
});
Try creating a function that runs on page load which selects the hyperlink with the same href
as the page.
Alternatively, load the main content of the page through AJAX as opposed to the traditional page location change. JQuery has a good AJAX implementation. Search online for jquery ajax
.
Another alternative would be to create a cookie onclick of the hyperlink, and set the selected one by reading the cookie. Although this would be very unreliable (back button, manual url entry, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With