0111010001110000 0111010001110000 - 1 month ago 14
CSS Question

jquery adding .active to bootstrap navbar

I have some issues with my existing jQuery when it comes to appending .active class to the Bootstrap navbar element, based on the browser url parameters.

The problem is that index.php will yield active class for the navbar element matching index.php however if no index.php is present the element will not be displayed as active, the same problem seems to occur when passing a query.

For example inbox.php will yield .active class, while inbox.php?view=sent will yield nothing.

Here is the existing jQuery can someone help me out to correct this tiny issues with index.php and / not displaying .active and same with links that contain query parameters for the same page.

$(document).ready(function () {
var url = window.location;
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().addClass('active');
});


The .nav structure is that of default Bootstrap navigation, nothing fancy. I have attempted to use PHP to append .active class but for some reason it did not want to play nicely and I used code that is found on StackOverflow regarding PHP and adding .active element.

Thanks in advance.

Answer

Assuming that all your pages have a path similar to .../myPage.ext?x=y, where ext is any given page extension i.e. php, html, etc., the following snippet gets the current page, removes the query string if any by splitting the window.location at '?' and gets the name of the current page, then it searches the nav-bar for the <a></a> with the matching href. Very similar to what you are doing.

<script>
    $(document).ready(function () {
        // Let's get rid of the query string
        var path = location.pathname.split('?')[0];
        var start = path.lastIndexOf('/') + 1;
        var activeLink = path.substr(start);

        var parent = $('a[href*="' + activeLink + '"]').parent('li');
        // These two lines check if you have dropdowns in your nav-bar
        if (parent.closest('ul').hasClass('dropdown-menu')) {
            parent.parents('.dropdown').addClass('active');
        }
        parent.addClass('active');
    });
</script>
Comments