Reputation: 275
I have a smooth page scrolling script but need it to add a class of “active” to the link that corresponds to the section of the page currently in view. I know there are a lot of similar posts about that, but they all only work when when the link itself is clicked. I would like the active class to be applied/removed not only on click, but when you scroll down the page with your mousewheel it should switch between the links accordingly with that method as well.
http://jsfiddle.net/pixeloco/sewcs4cr/
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - $('nav').height()
}, 1000);
return false;
}
}
(this link produces the result im going for, but when i tweak it to my needs to active class starts jumping... plus there are thing that seem to be defined but never used which confuses my non-js-saavy brain more than usual: http://jsfiddle.net/cse_tushar/Dxtyu/141/)
Upvotes: 1
Views: 266
Reputation: 275
alright found a solution to this so in case anyone else is ever in search of something similar i hope this helps: http://jsfiddle.net/pixeloco/L57z4ntb/
function checkSectionSelected(scrolledTo){
var threshold = 30;
var i;
for (i = 0; i < sections.length; i++) {
var section = $(sections[i]);
var target = getTargetTop(section);
if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
sections.removeClass("active");
section.addClass("active");
}
};
}
checkSectionSelected($(window).scrollTop());
$(window).scroll(function(e){
checkSectionSelected($(window).scrollTop())
});
Upvotes: 1