We were looking for a way to highlight navigation elements using scrollto.js, a jQuery snippet. We have 5 anchor links and as a user either clicks on one of the anchor links or scrolls to that particular section we’d like to highlight the current anchor link by adding a class. See below for a fairly simple and straight forward script to achieve this.
[cc lang=”js”]
$(function(){
var sections = {},
_height = $(window).height(),
i = 0;
// Grab positions of our sections
$(‘.section’).each(function(){
sections[this.name] = $(this).offset().top;
});
$(document).scroll(function(){
var pos = $(this).scrollTop();
// Look in the sections object and see if any section is viewable on the screen.
// If two are viewable, the lower one will be the active one.
for(i in sections){
if(sections[i] > pos && sections[i] < pos + _height){
$(‘a’).removeClass(‘active’);
$(‘#nav_’ + i).addClass(‘active’);
}
}
});
});
[/cc]