Reputation: 65
Hello I have a one page website which uses smooth scroll in the navigation I have also set up a function which applies the active class when the link is clicked and removes it from the otehr links but is there a way to add the active class to the correct link depending on where you are on the page e.g. if I scroll to energy saving section the main nav adds an active class to energy saving.
Here is my code I am using for the smooth scroll.
var smoothScroll = function() {
$('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 - $('.fd_PageHeader').height() - 40
}, 1000);
$('body').removeClass('navVisible navTransition');
return false;
}
}
});
};
Upvotes: 0
Views: 1161
Reputation: 2089
DIY solution:
Register an onScroll listener and for each callback compare the current scroll position to the vertical position of the headings.
$(document).scroll(function(){ /* callback here */ });
The vertical scroll position may be retrieved using jQuery.scrollTop(). The topOffset of the headings (offset().top) needs to be combined with the current window height: $(window).height();
prior to comparing.
See a POC version here http://jsfiddle.net/b1bc7wbL/
Easy solution:
Use a third party module like http://getbootstrap.com/javascript/#scrollspy
Upvotes: 1