28

I am trying to have a content block always be shown to the user, even if he scrolls way down the page. He should also be able to scroll up and down the content block. Here is a fiddle with a stripped down version to show you what I mean:

http://jsfiddle.net/9ehfV/2/

One should notice when scrolling down, until reaching the bottom of the red block, it will fix the block on the window, and when scrolling back up, it places it back.

In Firefox one can scroll up and down and the fixing/unfixing described above is imperceptible – smooth as silk.

Once one tries scrolling in Chrome or IE, though, it seems like the scroll event lags and one can see the block "glitching" for a second. It's not code lag – it seems to be something with the browsers.

Is there any way to fix this? I'm at my wit's end.

I'd appreciate suggestions on how I can achieve the same effect in a different way...thanks

jimmym715
  • 1,512
  • 1
  • 16
  • 25
Marcelo Mason
  • 6,750
  • 2
  • 34
  • 43
  • I'd guess it's something more to do with how Firefox has scroll easing and how Gecko/Rhino fires/interprets the scroll event differently from other browsers than anything else, so it will probably be something hard to fix still using the `scroll` listener approach, and I don't see any other possible approach atm, but best of luck man. – Fabrício Matté Jun 10 '12 at 08:24

2 Answers2

47

Since JavaScript runs in the same thread as the UI, a scroll event callback can block the UI-thread and thus cause lag. You need to throttle the scroll event listener because some browsers fire a lot of them. Especially if you're on OS X with an analog scroll device. Since you do a lot of height calculations in your listener, it will trigger a reflow (very expensive) for every scroll event that is fired.

To throttle the listener, you have to prevent the listener from firing every time. Usually you wait until the browser doesn't trigger an event for x milliseconds, or have a minimum time between calling your callback. Try adjusting the value to see the effect. Even 0 milliseconds can help, since it will delay the execution of the callback until the browser has time (usually 5-40 ms).

It's also a good practice to toggle a class to switch between states (static and fixed position) instead of hard-coding it in JavaScript. Then you have a cleaner separation of concerns and avoid potential extra redraws by mistake (see "Browsers are smart" section). (example on jsfiddle)

Wait for a pause of x ms

// return a throttled function
function waitForPause(ms, callback) {
    var timer;

    return function() {
        var self = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function() {
            callback.apply(self, args);
        }, ms);
    };
}

this.start = function() {
    // wrap around your callback
    $window.scroll( waitForPause( 30, self.worker ) );
};

Wait at least x ms (jsfiddle)

function throttle(ms, callback) {
    var timer, lastCall=0;

    return function() {
        var now = new Date().getTime(),
            diff = now - lastCall;
        console.log(diff, now, lastCall);
        if (diff >= ms) {
            console.log("Call callback!");
            lastCall = now;
            callback.apply(this, arguments);
        }
    };
}

this.start = function() {
    // wrap around your callback
    $window.scroll(throttle(30, self.worker));
};

jQuery Waypoints Since you're already using jQuery, I would have a look at the jQuery Waypoints plugin which has a simple and elegant solution to your problem. Just define a callback when the user scrolls to a certain waypoint.

Example: (jsfiddle)

$(document).ready(function() {
    // throttling is built in, just define ms
    $.waypoints.settings.scrollThrottle = 30;

    $('#content').waypoint(function(event, direction) {
        $(this).toggleClass('sticky', direction === "down");
        event.stopPropagation();
    }, {
        offset: 'bottom-in-view' // checkpoint at bottom of #content
    });
});
rstackhouse
  • 2,238
  • 24
  • 28
gregers
  • 12,523
  • 8
  • 46
  • 41
  • I understand where you're coming from. But can you show me a jsfiddle which would have the same functionality as mine, but provide the advantages you describe? – Marcelo Mason Jun 14 '12 at 21:32
  • I don't understand what specific functionality you're referring to. Do you want your code with class-toggling and throttling? – gregers Jun 14 '12 at 21:55
  • 2
    Oh, I see. The scroll-logic was a bit more complicated than I first though. Think it's necessary to do some computation in between fixed positions, but classes will simplify for the fixed positions. Updated jsfiddle here: http://jsfiddle.net/b5hU8/4/ – gregers Jun 14 '12 at 22:45
  • 1
    +1 for the link explaining reflows and repaints, didn't realize it was something I could optimize for. – Marcelo Mason Jun 15 '12 at 21:30
  • Split the synchronisation out of the scroll handler by reducing multiple scroll events to a meaningful app-event, like a location change. Listen for that event for triggering more costly update code. If reduction isn't possible, use one of these excellent throttle functions to fire the secondary event. That should help free up the scrolling animation. – captainpete Aug 27 '13 at 16:49
  • Hello. Sorry to bring up this old thread, but I can't implement this to my code. Do I put the above code inside or outside my function? :/ – scooterlord Jan 28 '14 at 00:09
  • @scooterlord You can have the `waitForPause` or `throttle` functions anywhere you like as long as it's available from the scope where you call it. The `this.start` code is just an example on how to use it with the questioners code, and should not be copied. Just notice how `throttle` and `waitForPause` is used. See the jsfiddle links for working examples. – gregers Feb 06 '14 at 14:06
  • 7
    This doesn't answer the question of lag in IE at all. sometimes throttle is the thing you DO NOT need, for example, when you need an absolute positioned element to follow your scrolling, it must be immediate. But is not on IE. – vsync May 18 '14 at 15:01
  • 1
    So did this solution actually fix the problem in Chrome for anyone? I tried several versions of it with no luck and though there are some positive responses to this answer and though it is the accepted answer, I haven't actually seen anyone confirm that it solved the problem. Thanks! – Hendeca Mar 14 '15 at 23:53
  • 3
    This answer might help people fix different problems, but the **choppy/laggy scroll** animation in IE is **not** solved by throttling the scroll event. – Oliver Apr 20 '15 at 18:09
1

Have you tried some jquery plugin for scrollbar or uses animation to scroll down and up? It will force all browsers to work at the same way (or closes enought)..

What happens is that firefox (at least v12) have a "native" scroll animation. When you navigate for any URL you can notice the smoothness for scroll actions and this is not implemented in other browsers, like Chrome or IE.

Examples for jquery scroller plugins:

Rafael Verger
  • 1,751
  • 13
  • 18
  • Doesn't help. Those plugins use the same scroll event, neither actually give smooth scrolling to the browsers that don't have it. Nor fix the glitching. – Marcelo Mason Jun 14 '12 at 15:36
  • These plugins are just an example. There are many other in a simple google searh for jquery scroll plugin. What you need is to use these plguins without the defaul scroll event... you will need to "remove" scrollbar and do your own scroll with scrollTo animation and easing plguin... like this http://stackoverflow.com/questions/4710438/how-to-use-easing-in-the-jquery-plugin-jquery-scrollto do you need a code example? – Rafael Verger Jun 14 '12 at 16:29