Firefox scrollTop problem

user621950 picture user621950 · Feb 17, 2011 · Viewed 8.4k times · Source

I have a problem with Firefox scrollTop value and onscroll event. This works great in IE, Safari and Chrome but Firefox seems to lag.

I tried to update some background position with the onscroll event, but when I take the handle and drag it up and down quickly, Firefox stops updating the scrollTop value and it causes some lag in my app.

You can try this code and look in the Firefox console when dragging the handle and you will see the values something stops the updating :

function SaveScrollLocation () {
    console.log(document.documentElement.scrollTop);
}

window.onscroll=SaveScrollLocation ;

Any idea how to make Firefox respond more quickly?

Answer

unclenorton picture unclenorton · Feb 17, 2011

There are two ways to handle this - throttle (execute the function with a set interval) and debounce (execute the function after the specified time has passed since the last call). You'll probably want to use throttling in your situation.

A simplified solution may look something like this (Updated: see it at http://jsfiddle.net/yVVNU/1/):

    window.onscroll=catchScroll;
    var timeOutId = 0;
    var jitterBuffer = 200;
    function catchScroll()
        {
            if (timeOutId) clearTimeout (timeOutId);
            timeOutId = setTimeout(function(){SaveScrollLocation()}, jitterBuffer);
        }

    function SaveScrollLocation () {
        console.log(document.documentElement.scrollTop);
        alert('scrolled');
    }

You can also use this jQuery plugin: http://benalman.com/projects/jquery-throttle-debounce-plugin/