Multiple nav sections all with the same links. The active section is shown in the first nav via an active class (.active). I’d like to highlight the same link in the subsequent nav sections.
Originally, I used a cloning method (credit due to you fine people, jQuery replaceWith() each element with the first) and although it worked perfectly, it interfered with some other functions (because it removes the original elements from the page and replaces them).
So, I need to figure out another, clever way to check the active class of the first section, find the matching links in the subsequent sections, and apply the class.
I’m thinking something like this… but something efficient and less ugly. The answer below does work.
HTML:
<nav class="postNav">
<ul>
<li class="active"><a href="#pageHeader">link to header</a></li>
<li><a href="#one">link to other posts</a></li>
<li><a href="#two">link to other posts</a></li>
<li><a href="#three">link to other posts</a></li>
<li><a href="#four">link to other posts</a></li>
<li><a href="#five">link to other posts</a></li>
</ul>
</nav>
JavaScript:
var navs = $('.postNav'),
first = navs.first(),
active = first.find('.active a').attr('href'),
anchrs = navs.not(first);
anchrs.find('li').removeClass('active');
anchrs.find('a[href=' + active + ']').parent().addClass('active');
UPDATE
Maybe by seeing which child in the index is active? Then I don’t need to filter by the anchor…
UPDATE + Final Answer
My Selector cached version of jfriend’s answer:
var nav = $('.postNav'),
first = nav.filter(':eq(0)'),
notF = nav.filter(':gt(0)'),
index = first.find('.active').index();
notF.each(function(){
$(this).find('li').removeClass('active').eq(index).addClass('active');
});
You can do it like this using the index position of an
liwithin itsuland jQuery’s.index()and.eq()makes that easier:Working demo: http://jsfiddle.net/jfriend00/dWaCn/
This works as follows: