Some very helpful folks wrote and then modified a script to change the class on a nav item when scrolling the page to a related section. Here’s the original post: Use jQuery to change a class dependent on scroll position.
My first issue is that the last section of the array is being ignored. Someone else had this question and a solution was offered, which worked for them, but not for me: jQuery class change based on scroll ignoring last section.
The second issue is that even setting aside that the last section in my array is not ever getting selected, the new class name is only getting added to my nav items, but never removed, so that by the time I scroll to the bottom of the page, every item except the last in my nav has “selected” as a class. I’d really appreciate any insight. Here’s my code, which is virtually identical to the modified version, except I’m using headings rather than sections (which is maybe significant?):
var $anchs = $('.content h1');
var $navs = $('#zone-submenu div .content > .item-list > ul > li');
topsArray = $anchs.map(function(){
return $(this).position().top - 100;
}).get(),
topsArray.push(window.height);
var len = topsArray.length;
var currentIndex = 0;
var getCurrent = function( top ) { // take the current top position, and see which
for( var i = 0; i < len; i++ ) { // index should be displayed
if( top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1] ) {
return i;
}
}
};
$(document).scroll(function(e) {
var scrollTop = $(this).scrollTop();
var checkIndex = getCurrent( scrollTop );
if( checkIndex !== currentIndex ) {
currentIndex = checkIndex;
$navs.eq( currentIndex ).addClass("selected").siblings(".selected").removeClass(".selected");
}
});
I’m afraid I can’t post the site itself – it’s in development and I can’t reveal it before it goes live. Thanks for any help, though!
This looks a bit odd:
From what I can tell in your code, it should be:
UPDATED
Fixing the “not displaying the last index item” …
You are referencing an invalid array element in your
getCurrentfunction – [i+1] is invalid when i == len-1. You need to just return the last element if that happens.