Reputation: 783
I have a page with different sections that can be scrolled to or accessed by clicking the corresponding link in the navbar. A demo of the page is on codepen http://codepen.io/meek/pen/NNprYb?editors=1010
I am using the following code to keep track of which section the user is scrolling over and highlighting it in the navbar
$(window).on("scroll", function() {
var currentPos = $(window).scrollTop();
$('.nav li a').each(function() {
var sectionLink = $(this);
var section = $(sectionLink.attr('href'));
if(section.position().top <= currentPos && section.position().top + section.height() > currentPos) {
$('.nav li').removeClass('active');
sectionLink.parent().addClass('active');
}
else {
sectionLink.parent().removeClass('active');
}
});
});
It works fine, but there is a gap where scrolling through between home and about sections, none of the links are highlighted. I have a feeling this might be because of the space the navbar occupies between home and about, but I'm not sure how to overcome this. Ideally, I'd like to have that gap also highlight "about".
I've tried to add this to the above code:
else if($('#nav-wrapper').position().top <= currentPos && $('#nav-wrapper').position().top + $('#nav-wrapper').height() > currentPos) {
$('.nav li').removeClass('active');
$('#temp').addClass('active');
}
but it doesn't work. Help appreciated
Upvotes: 0
Views: 308
Reputation: 491
Solution:
Adjust your if
statement in your scroll
event to match the following.
if(section.position().top <= currentPos && sectionLink.offset().top + section.height() > currentPos)
The key being, the second instance of section.position().top
changes to sectionLink.offset().top
Upvotes: 1