Skip to content

Instantly share code, notes, and snippets.

@Didier-Vaerman
Created May 12, 2016 14:57
Show Gist options
  • Save Didier-Vaerman/ef75691c894ed6533831b986f6156256 to your computer and use it in GitHub Desktop.
Save Didier-Vaerman/ef75691c894ed6533831b986f6156256 to your computer and use it in GitHub Desktop.
If element is in view, get href from link then substrat href before hash to find the link to add active class + Scroll to anchor
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.parents().offset().top - 100},'slow');
}
var sections = $('.content-section')
, nav = $('.page-navigation')
, navLink = nav.find('a').attr('href')
, navHash = navLink.substr(0,navLink.indexOf('#'))
, nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
var marker = $(this).children('.marker').attr('name');
nav.find('a[href="'+ navHash +'#'+ marker +'"]').addClass('active');
}
});
});
$('.page-navigation li a').on('click', function (e) {
$('.page-navigation li a').removeClass('active');
$(this).toggleClass('active');
var link = $(this).attr('href');
var hash = link.substring(link.indexOf('#')+1);
scrollToAnchor(hash);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment