This code works and does the job, but it's poor, rudimentary and has some issues with the scrolling event. Can somebody help me to optimize the scrolling event?
Structure and desired behaviour:
- There are two containers,
.layout__left
(red) and.layout__right
(green). - The green container will have the main content and will scroll normally.
- The red container will have the navigation so it will have less content and should scroll up to a certain point only, until the menu reaches the border of the page.
This is what I am doing:
- First both containers scroll normally.
- When scrolling down the red container, if the scroll position + window size is bigger than the li:last child position (couldnt think of anyway to detect the "bottom"), then the container has a position fixed.
- When scrolling up, the fixed position is disabled and when the menu reaches the top of the document, the position is fixed again, and then removed.
As I said, it does the job, but, it's slow and has glitches while scrolling. I think it's because I am doing on the scroll event on every pixel change.
I tried throttling the function call, but the code doesn't function at all:
$(window).on('scroll', function() {
$.throttle(100, sectionScroll));
});
sectionScroll = function() {
var lastScrollTop = 0, delta = 5;
var left = $('.layout__left');
var right = $('.layout__right');
var scroll = $(this).scrollTop();
var viewport = $(window).height();
var lastChild = $('.navigation > ul > li:last-child').offset().top;
if(Math.abs(lastScrollTop - scroll) <= delta)
return;
if (scroll > lastScrollTop){
// SCROLL DOWN
left.removeClass('top absolute');
// if the last item of the left is visible
if ( (scroll + viewport) > (lastChild + 30) ) {
// make the left fixed
left.addClass('fixed bottom');
console.log("bottom!");
}
// SCROLL UP
} else {
// remove fixed class from left
left.removeClass('fixed bottom');
left.addClass('absolute bottom');
if ( scroll <= left.position().top ) {
left.removeClass('bottom absolute');
left.addClass('top fixed');
left.removeClass('top fixed');
console.log("top!");
}
}
lastScrollTop = scroll;
};
Any feedback?