Adding a class to a navigation menu
May not be exactly what the title of this thread is, but it is the best I can sum it up. Anyways, I have a few lines of jQuery that takes a navbar and as the user scrolls down the page, the navbar changes to reflect where on the page the user is (example here). The code that is highlighted is what I am having trouble with. My goal is to get the navbar to stick to the page after the user scrolls down for a set amount of pixels.
Also on a side note, if you see anything that needs to be improved go ahead and provide feedback.
Code:
var sections = $('section')
, nav = $('nav')
, nav_height = nav.outerHeight();
$(window).scroll(function() {
var cur_pos = $(this).scrollTop();
if (cur_pos >= 300) {
$('nav').addClass('stickme');
}
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;
});