I have the following scroll event that on scroll measures where in the page the user is and updates the navigation styling according to which section they are in. The problem is the calculation i'm performing on scroll is quite chunky and it slows down the page a little bit when scrolling. Here is my code:
screenHeight = $(window).height();
screenHeightRatio = screenHeight*0.3;
//here I calculate screen height plus the ratio of the screen height I would like for the menu elements to change
aboutOffset = $(".aboutcontainer").offset().top - screenHeightRatio;
portfolioOffset = $(".portfoliocontainer").offset().top - screenHeightRatio;
musicOffset = $(".musiccontainer").offset().top - screenHeightRatio;
contactOffset = $(".contactcontainer").offset().top - screenHeightRatio;
// here I calculate the offset for each section in the screen
$(window).scroll(function(){
var amountScrolled = $(document).scrollTop();
//here I see how far down the page the person has scrolled
if($(".header-options").hasClass("portfolio-inner-active")) {
return;
// here I cancel the scroll event if they are in a certain section
} else {
if(contactOffset <= amountScrolled) {
// each of the following if statements will calculate if the amount scrolled surpasses the various section offsets I defined outside of the scroll function
$(".header-options li").removeClass("active");
$(".contactbutton").addClass("active");
history.pushState('page2', 'Title', '/contact');
return;
} else {
if(musicOffset <= amountScrolled) {
$(".header-options li").removeClass("active");
$(".musicbutton").addClass("active");
history.pushState('page2', 'Title', '/music');
return;
} else {
if(portfolioOffset <= amountScrolled) {
$(".header-options li").removeClass("active");
$(".portfoliobutton").addClass("active");
history.pushState('page2', 'Title', '/portfolio');
return;
} else {
if(aboutOffset <= amountScrolled) {
$(".header-options li").removeClass("active");
$(".aboutbutton").addClass("active");
history.pushState('page2', 'Title', '/about');
}
}
}
}
}
});
Would love to know if there is a less cpu hungry way of doing this as I really want this effect on the site.
Cheers