Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make "scrollLeft" / "scrollTop" changes not trigger scroll event listener

Currently my program is in a spot where it both listens for the user to scroll a certain element, but also, at times, automatically scrolls this element by itself. (Not a gradual, pretty scroll, but an instant jump. It makes sense in context, I swear.)

Is there a way to make the scroll event not trigger if the scrolling was done by setting scrollLeft or scrollTop? My first thought was a basic switch, like:

ignoreScrollEvents = true; element.scrollLeft = x; ignoreScrollEvents = false;  function onScroll() {   if(ignoreScrollEvents) return false; } 

but since events don't trigger immediately (oops, duhh), that's not a workable solution. What other sort of answers could I try? I'm also using jQuery, if that helps anything.

like image 988
Matchu Avatar asked Sep 06 '09 20:09

Matchu


People also ask

Does scrollIntoView trigger scroll event?

scrollIntoView does not trigger mousewheel nor scroll event in Angular. Bookmark this question.

Which event does a scrollbar component cause?

The scroll event fires when you scroll a webpage or an element. For a page, the scrollX and scrollY properties return the number of pixels that the document is currently scrolled horizontally and vertically.

How do you stop an Onscroll event?

The window. onscroll event fires when the window has been scrolled. Overriding this function and setting it to a fixed position every time the scroll happens will effectively disable the scroll effect.

What is $( window scrollTop ()?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.


1 Answers

Easiest generic method? Just reset the flag in the event handler. You'll want to check first if you're actually changing the value, as otherwise an event won't be fired - as Rodrigo notes, a good practice here is to factor this out into so-called "setter" functions:

function setScrollLeft(x) {   if ( element.scrollLeft != x )   {     ignoreScrollEvents = true;     element.scrollLeft = x;   } }   ...  function onScroll()  {   var ignore = ignoreScrollEvents;   ignoreScrollEvents = false;    if (ignore) return false;    ... } 

But, depending on your needs, you may already be storing the scroll position somewhere; if so, just update and check that as your flag. Something like:

element.scrollLeft = currentScrollLeft = x;  ...  function onScroll()  {   // retrieve element, etc...     if (element.scrollLeft == currentScrollLeft) return false;    ... } 
like image 148
Shog9 Avatar answered Sep 22 '22 11:09

Shog9