Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change (add) the active state class to a navigation link

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?

like image 995
Nistor Alexandru Avatar asked Feb 19 '23 22:02

Nistor Alexandru


2 Answers

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');
  });
like image 112
Engineer Avatar answered Mar 09 '23 01:03

Engineer


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).

like image 37
jaypeagi Avatar answered Mar 09 '23 01:03

jaypeagi