user2756554
user2756554

Reputation:

Add class to active page does not work for pages in sub folders

I have the following script that add a class .active to the current page:

//Main menu .active classes handler
    $("#mainMenu a").filter(function () {
        var href = location.href.replace(/#*/, "");
        if (location.pathname === "/") {href += "index";}
        return href === this.href;
    }).addClass("active");

Everything works fine for the pages in the main directory but it does not work for the pages in sub folders, for example:

It works for <a href="index.php">Home</a> but it won't work for: <a href="sub/test.php">Home</a> Why is that? Do I need to add something like "last of index"?

Full HMTL:

<li><a href="index">Home</a></li>
<li><a href="about">About</a></li>
<li class="subMenu"><a href="gallery">Gallery</a>
    <ul>
        <li><a href="sub/test">Page in a sub folder</a></li>
    </ul>
</li>
<li><a href="contact">Contact</a></li>

Upvotes: 0

Views: 164

Answers (2)

user2756554
user2756554

Reputation:

I solved the problem by adding <base href="/"> in my head. It works like magic!

Upvotes: 0

helion3
helion3

Reputation: 37381

The error isn't in your code, but rather the fact that you're including the site javascript using relative paths:

When you visit /testing/test the javascript files return as 404 because they're relative.

assets/js/main.js becomes /testing/test/assets/js/main.js

Just use absolute paths or you can look into setting the base href

You should use a developer console like Firebug or Chrome dev tools to watch for any errors. I immediately saw 404 errors and noticed it was your js file.

Upvotes: 1

Related Questions