Dev
Dev

Reputation: 1561

Needs to toggle 'active' class when navigation list items are selected

I am using twitter bootstrap and trying to set 'active' class to the navigation list item by using jquery when a list item is selected.

Below is my code

            <ul class="nav nav-pills pull-right">
              <li id="home"><a href="/">Home</a></li>
              <li id="gadget"><a href="/category/gadgets"><span>Gadgets + Geeky</span></a></li>
              <li id="toys"><a href="/category/toys"><span>Toys</span></a></li>
              <li id="wearables"><a href="/category/wearables"><span>Wearables</span></a></li>
              <li id="home_office"><a href="/category/home-office"><span>Home + Office</span></a></li>
              <li id="food_drinks"><a href="/category/food-drinks"><span>Food + Drinks</span></a></li>
              <li id="kids"><a href="/category/kids"><span>Kids Stuff</span></a></li>
            </ul>
            <script>
              $( document ).ready(function() {
                 $('ul li').click(function() {
                    // remove classes from all
                    $('li').removeClass('active');
                    // add class to the one we clicked
                    $(this).addClass("active");
                 });
              });
            </script>

But when i click on a list item, temporarily active class is getting set on the navigation item, but the page is getting refreshed and showing the current clicked list item without active class.

i have followed the instructions mentioned in Toggle active class in nav bar with JQuery with no success.

Could someone point out what i am missing.

Thanks

Upvotes: 1

Views: 1877

Answers (1)

ssilas777
ssilas777

Reputation: 9754

This script runs after redirection happens, so this should work for you. We are adding a dummy class 'activeLink' to the active link and select the list based on that active link.

 $(function(){
        $('ul li a').removeClass('activeLink');
        var url = window.location.pathname, 
            // create regexp to match current url pathname also to match the home link
            urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/,'')); 
            // now grab every link from the navigation
            $('.ul li a').each(function(){
                // and test its normalized href against the url pathname regexp
                if(urlRegExp.test(this.href.replace(/\/$/,''))){
                    $(this).addClass('activeLink');
                }
            });

           $('li').removeClass('active');
           $('a.activeLink').closest('li').addClass('active');
    })

;

Upvotes: 1

Related Questions