• Skip to main content
  • What We Do
  • Our Work
  • Contact

Mackey

August 28, 2012 by Mackey

Add Class to Anchor Link for Scrolled To Element – jQuery

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]

Filed Under: Code Snippets

Mackey Creative Lab
Web Design and Development, Branding, Graphic Design and Marketing Strategy
680 East Colorado Blvd., Suite 180 & Second Floor, Pasadena, CA 91101
info@mackeycreativelab.com // 626 214 5093
© 2014-2021 Mackey, LLC, All Rights Reserved

Want to join the Lab? Become a lab partner

Need Wordpress Performance & Security Management? Learn More