Skip to content

Instantly share code, notes, and snippets.

@boye
Created February 14, 2014 15:48

Revisions

  1. boye created this gist Feb 14, 2014.
    56 changes: 56 additions & 0 deletions perfscroll.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <meta charset="utf-8">
    <title>Perfscroll jQuery plugin</title>
    </head>
    <body>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <script>
    $(function () {

    // Small plugin to implement a performant scroll listener
    // Based on an idea by John Resig
    // @see: http://ejohn.org/blog/learning-from-twitter/
    $.fn.perfscroll = function (fn, interval) {
    var didScroll = false,
    evt = null;

    $(this).on('scroll', function (e) {
    evt = e;
    if ( !didScroll ) {
    didScroll = true;
    }
    });

    setInterval($.proxy(function () {
    if ( didScroll ) {
    didScroll = false;
    if ( fn && $.isFunction(fn) ) {
    fn.apply(this, [evt]);
    }
    }
    }, this), interval || 250);

    };

    // Example
    $(window).perfscroll(function (e) {
    console.log(this.scrollTop());
    // console.log(e); <-- onscroll event object
    // console.log(this) <-- points to element
    // ^ this means you can do someting like: if (this.scrollTop()>10) {}
    });

    });
    </script>
    </body>
    </html>