marb
marb

Reputation: 53

Setting active link dynamically on static navigation

I have "navigation.html" (static coded navigtaion ) file loaded on multiple pages, using jQuery .load() Now I need to dynamically set active <li> for each page user clicking on. I can not use body id for specific reasons. Any other ways to do this?

Upvotes: 0

Views: 903

Answers (3)

h4cky
h4cky

Reputation: 894

If you can identify your current page by class or id (ex: body > div#contacts) for contacts.html and this class/id is unique then you have to match it with you navigation, other way is to match window.location.href value (parsed if you want) against your navigation.

changeActiveLink is defined in JS (ex:init.js) file which you include to each page

function changeActiveLink() {
  var currentLocation = window.location.href;
  currentLocation = currentLocation.replace('//', '/').split('/');
  var page = currentLocation[currentLocation.length - 1];

  if (page == "") { page = 'index.html'; }

  $('#leftNav1 a[href*="'+ page +'"]').addClass('active');
}

This line is called from each file when "init.js" is included.

$('#leftNav1').load('navigation.html', changeActiveLink);

Upvotes: 1

autumncollection
autumncollection

Reputation: 61

Or you can use any HTML or even HTML5 tag to specify li item.

  <li class="some">

or

  <li title="some">

or

  <li attr-specify="some-specific-in-url">

and jQuery with window.location object $('li[title="' + window.location.path + '"]').addClass("active");

Upvotes: 1

bretterer
bretterer

Reputation: 5781

You could set up some jquery script to get the url and then find the href of the li that matches that. This will allow you to addClass() to that li of active.

This of course will only work if your href matches the url

Upvotes: 0

Related Questions