Question

So I am using Twitter Bootstrap 3 to build my front-end, in this case simple tabbed menu. I was struggling a lot to make it work, because menu links didn't want to highlight properly when you click on them. By that I mean, if you for example click on the page about.php that link should be marked as active and therefore have some CSS styling applied on it. I saw many posts here on stackowerflow but they only partially worked for me. For example some jQuery code that people posted would do proper highlighting but would prevent links from working.

Finally I have found a solution that is working great except when I use pagination. Let me explain:

Here is the bootstrap html code of my menu:

    <nav class="row">
    <ul class="nav nav-tabs nav-justified">
        <li><a href="index.php"> Home </a></li>
        <li><a href="about.php"> About Us </a></li>
        <li><a href="contact.php"> Contact Us </a></li>
        <li><a href="services.php"> Our Services</a></li>
        <li><a href="portfolio.php"> Portfolio </a></li>
    </ul>
<nav>

In order to make menu highlighting working I am using this javaScrpt code:

var url = window.location;
// Will only work if string in href matches with location
$('ul.nav a[href="' + url + '"]').parent().addClass('active');

// Will also work for relative and absolute hrefs
$('ul.nav a').filter(function () {
    return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active'); 

So when I start the app index.php is marked as active and that is great, if I click on about.php I will go to that page and it is also marked as active, that is great too. But since I have pagination on index.php, and I click on Pagination link 2 url will change to: index.php?page=2, and highlighting will break, index.php will not be marked as active anymore.

Do anyone know what is going on here, and what can we do to fix this ? I'm not that good with JS.

Was it helpful?

Solution

Rather than just using window.location for your url, try using:

var url = window.location.pathname;

If your current url is www.mywebsite.com/index.php?page=2 the above should output /index.php.

You can use url.replace('/', '') to get rid of that first slash.

EDIT:

Since your pathname may have multiple parts, such as /something/index.php we need to deal with that. Another way of doing it is:

var urlpath = window.location.pathname;

In your code you have:

$('ul.nav a[href="' + url + '"]').parent().addClass('active');

You can change the selector to:

$('ul.nav a[href="' + urlpath.split('/').pop() + '"]').parent().//...etc

This is doing the splitting and isolating the index.php portion in one go. index.php will of course be contact.php or whatever.php on other pages.

Try this JSFiddle I just created, showing the above line in action: http://jsfiddle.net/N9SHq/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top