jQuery active menu link to index page is always active

607 views Asked by At

I have a menu that uses the following jQuery to add the class active to highlight the current page.

<script>
    jQuery(document).ready(function($) {
        $(function() {
            setNavigation();
        });

        function setNavigation() {
            var path = window.location.pathname;
            path = path.replace(/\/$/, "");
            path = decodeURIComponent(path);

            $(".nav a").each(function() {
                var href = $(this).attr('href');
                if (path.substring(0, href.length) === href) {
                    $(this).closest('li').addClass('active');
                }
            });
        }
    });
</script>

This is my HTML:

<ul class="nav">
    <li><a href="/wordpress">Portfolio One</a></li>
    <li><a href="/wordpress/portfolio-two">Portfolio Two</a></li>
    <li><a href="/wordpress/portfolio-three">Portfolio Three</a></li>
    <li><a href="/wordpress/bio-contact">Bio / Contact</a></li>
</ul>

As you can see the first link (Portfolio One) Links to the main page. This is causing that this link always has the class active regardless what page the menu is on.

Can anyone provide some insight into amending my jQuery so it gets the full link and excludes only partial matches?

2

There are 2 answers

0
Sushil On BEST ANSWER

The reason your links in the menu always have an active class is because it's not being removed for inactive links. you can try adding $('.nav li').removeClass('active'); this will first remove the active class and then you can add the active class for the current active link.

here's the updated code.

function setNavigation() {
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");
    path = decodeURIComponent(path);

    $(".nav a").each(function() {
        $('.nav li').removeClass('active'); // remove active for all links
        var href = $(this).attr('href');
        if (path.substring(0, href.length) === href) {
            $(this).closest('li').addClass('active');
        }
    });
}
0
nalinc On

How about including another condition in the if-construct before adding the class

if (path.substring(0, href.length) === href && path.length == href.length)