This code works and does the job, but its EXTREMMELY is poor + rudimentary and has some issues with scrolling events. Can someone help me optimize the scroll event?
Prototype: http://codepen.io/rootion/pen/gpZZpG
Structure and desired behavior:
- 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 navigation, so it will have less content and should scroll to a certain point until the menu reaches the page border.
This is what I do:
- At first, both containers scroll normally.
- When scrolling down the red container, if the scroll position + window size is larger than the personal position li: the last child position (in any case, could not find the "bottom"), then the container has a fixed position.
- When scrolling, the fixed position is turned off, and when the menu reaches the top of the document, the position is fixed again and then deleted.
As I said, this does the job. But it is slow and has glitches when scrolling. I think this is because I do it on a scroll event and execute on every pixel.
I tried throttling a function call, but the code doesn't work 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){
Any feedback?
source share