JQuery: How can I improve on this scroll event that fires too many times?

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){ // 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?

+5
source share
1 answer

One way to do this is to put this in your script:

 var isStarted = false; 

Then in your launch function:

 if(!isStarted) { isStarted = true; //other stuff } else { return false; //because it already doing it thing } 

In your stop function:

 isStarted = false; 
0
source

All Articles