Make "scrollLeft" / "scrollTop" changes not trigger scroll event listener
Solution 1:
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;
...
}
Solution 2:
How about a setter?
var _preventEvent = false; // set global flag
function setScrollTop(amount) {
_preventEvent = true; // set flag
document.documentElement.scrollTop = amount * Math.random();
}
function setScrollLeft(amount) {
_preventEvent = true; // set flag
document.documentElement.scrollLeft = amount * Math.random();
}
// scroll event listener
window.onscroll = function() {
console.clear();
if (_preventEvent) {
_preventEvent = false; // reset flag
return;
}
console.log('normal scroll');
}
html{ height:500%; width:500%; }
button{ position:fixed; }
button + button{ top:50px; }
<button onclick=setScrollTop(1000)>Random scrollTop</button>
<button onclick=setScrollLeft(1000)>Random scrollLeft</button>