Window scroll event causing IE to lag behind when using the mouse wheel

I have a navigation container at the top of the page that should add or remove the class name โ€œstuckโ€ (switching between position: static and position: fixed) when the page scrolls beyond a certain value. It seems to work fine in FF and Chrome, but of course, IE (7.8 and 9) has problems.

When scrolling with the mouse wheel, the page lags strongly (essentially unusable), although if I grab and drag the scroll bar in the horizon, the page will glide smoothly without delay.

My searches showed that, probably, because IE executes a lot more scroll events than other browsers, but I canโ€™t determine exactly how to reduce the number of triggered events. In the code block below, you can see that I also use the โ€œscroll stopโ€ solution, but I really need to also execute the WHILE callback when the user is still scrolling, when it goes beyond a certain point on the page.

I thought the way I executed it was pretty sophisticated and truncated and basic, but is there a better way to handle this, at least only for IE?

var scrollValue = 0; var scrollTimer = false; $(window).bind('scroll', function(){ scrollValue = $(window).scrollTop(); // SET TIMER DELAY FOR SCROLL-STOP if (scrollTimer) { clearTimeout(scrollTimer); } scrollTimer = setTimeout(scrollStopped, 25); // STICK/UNSTICK HEADER if (scrollValue > 320){ if (!$(stickyWrap).hasClass('stuck')){ $(stickyWrap).addClass('stuck') } } else { if ($(stickyWrap).hasClass('stuck')){ $(stickyWrap).removeClass('stuck'); } } }); 
+4
source share
1 answer

Down with a timeout, with a switch

If you made jQuery a little simpler and added a switch to only do something once before and after the threshold, it should speed up the process quickly.

 var header = $('.stickyWrap'), trig = 320, go = true; $(window).bind('scroll', function(){ var scrollValue = $(this).scrollTop(); if ((go && scrollValue > trig) || (!go && scrollValue <= trig)) {//before or after header.toggleClass('stuck');//toggle class go ? go = false : go = true;//toggle boolean } }); 

Now he will try to do something only once before and once after he crosses threshold 320 .

Made a fiddle>

+1
source

All Articles