The forum of the forums

Would you like to react to this message? Create an account in a few clicks or log in to continue.
The forum of the forums
2 posters

    How to Add Active Class to navbar

    Mati
    Mati
    Active Poster


    Posts : 1932
    Reputation : 333
    Language : HTML, CSS & JavaScript
    Location : Forum Services

    Solved How to Add Active Class to navbar

    Post by Mati September 21st 2015, 9:59 am

    How do I add “active class” to the menu item with jQuery that links to the page on which the visitor or user is.


    Last edited by Mati on September 21st 2015, 11:53 am; edited 1 time in total
    Ange Tuteur
    Ange Tuteur
    Forumaster


    Male Posts : 13207
    Reputation : 3000
    Language : English & 日本語
    Location : Pennsylvania

    Solved Re: How to Add Active Class to navbar

    Post by Ange Tuteur September 21st 2015, 11:25 am

    It depends on the version of the forum you're asking for, but the typical way of checking is a clean URI against a clean href attribute.

    Here's an example that should work on most default forum versions.
    Code:
    $(function() {
      var cleanURI = window.location.href.replace(/\?.*|#.*/, ''), // get the clean URL without queries or hashes
          menu = $('a.mainmenu'), // get menu items
          i = 0, // set index
          j = menu.length; // cache menu length

      // loop menu links
      for (; i < j; i++) {
        // clean the href and compare it with the window location
        if (menu[i].href.replace(/\?.*|#.*/, '') == cleanURI) {
          menu[i].className += ' activeNav'; // add a new class
          break; // break out of the loop because we found our match
        }
      }
    });

    Then you can style the navigation link with CSS :
    Code:
    a.mainmenu.activeNav {
      background:#39C;
    }
    Mati
    Mati
    Active Poster


    Posts : 1932
    Reputation : 333
    Language : HTML, CSS & JavaScript
    Location : Forum Services

    Solved Re: How to Add Active Class to navbar

    Post by Mati September 21st 2015, 11:55 am

    Thanks this works perfect Smile
    Ange Tuteur
    Ange Tuteur
    Forumaster


    Male Posts : 13207
    Reputation : 3000
    Language : English & 日本語
    Location : Pennsylvania

    Solved Re: How to Add Active Class to navbar

    Post by Ange Tuteur September 21st 2015, 11:57 am

    No problem. Smile

    Topic archived

    Have a nice day. ^^

      Current date/time is November 11th 2024, 8:14 pm