Having some trouble with my javascript, specifically with the navigation links. The code is supposed to apply an active class to the nav links when on that section of the page, but it's glitchy and flickers while scrolling instead of remaining active. Check out this JSFiddle for reference here. If you scroll slowly, you'll notice the "home" link briefly becomes active. I want each link to remain active after being clicked and throughout that entire section of the page.
I also have a sticky nav bar and smooth scrolling enabled with javascript, so I suspect there might be some conflict there. Any help would be greatly appreciated.
Here is the snippet of Javascript attempting to assign the active class:
var sections = $('section')
, nav = $('nav')
, 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');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
nav.find('a').on('click', function () {
var $el = $(this)
, id = $el.attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - nav_height
}, 500);
return false;
});