0 Replies - 4733 Views - Last Post: 15 February 2014 - 06:15 AM

#1 andrewsw  Icon User is online

  • lashings of ginger beer
  • member icon

Reputation: 6340
  • View blog
  • Posts: 25,565
  • Joined: 12-December 12

[jQuery] Style top-level of multi-level navbar

Post icon  Posted 15 February 2014 - 06:15 AM

This jQuery snippet applies a css class-name to the top-level of a multi-level navigation-bar, for the level(s) that contain the link to the current page.

$(function() {
   var url = window.location.href;
   var page = url.substr(url.lastIndexOf('/')+1);
   
   $('ul#main-nav a[href*="'+page+'"]')
        .parents('li:last')
        .children('a')
        .first()
        .addClass('active');
});

var url = window.location.href; get the current page's address.

var page = url.substr(url.lastIndexOf('/')+1); gets just the page's filename, such as 'page1.html'.

$('ul#main-nav a[href*="'+page+'"]') 'main-nav' will be the id you have given your navigation bar. This collects the a-links that contain your current page's address. The asterisk '*=' finds any links containing the text of the variable page. '$=' would look specifically for links that end-with this text.

.parents('li:last') this collects all the li's that are parents to these a-links. They are collected backwards, so the top-level li is the last one added.

.children('a').first() this assumes that your top-level li contains an a-link. This is quite common, but it could be a 'span' or other element. If appropriate you could just add a class-name to 'li:last' but be aware that its styles could be inherited by its children.

.addClass('active'); don't try and apply individual style-rules, just use a class-name such as 'active' or 'current'.

Here is sample HTML to test with:

Spoiler

Using url.substr(url.lastIndexOf('/')+1) may not be sufficient; if there are url parameters or other additions such as 'page1.html#someid' then these will need to be stripped from the page variable. This can be achieved with:

page = page.split(/[#?]/)[0];



Is This A Good Question/Topic? 2
  • +

Page 1 of 1