Matt's Blog

Endless Scroll (a.k.a. Endless Page) with jQuery

by Matt Hodan on August 28, 2011

I decided to write a super lightweight endless scroll (a.k.a. endless page, pageless, without pagination, etc.) plugin for jQuery. It will let me trigger some code whenever the user scrolls within a certain number of pixels from the bottom of the page.

I’ll get right to the juicy details. Here is the plugin code, and yes, it is written in CoffeeScript. If you need javascript, feel free to copy and paste this code into jashkenas awesome CoffeeScript parser.

(($) ->
  $.fn.nearBottom = (options) ->
    defaults = {
      pixelsFromBottom: 100,
      delay: 250,
      callback: -> false
    }
    options = $.extend defaults, options

    do checkScrollPosition = ->
      documentHeight = $(document).height()
      scrollHeight = $(document).scrollTop()
      windowHeight = $(window).height()
      pixelsToBottom = documentHeight - scrollHeight - windowHeight

      scrollable = ->
        documentHeight > windowHeight

      nearBottom = ->
        pixelsToBottom <= options.pixelsFromBottom

      enqueueNextCheck = (delay) ->
        setTimeout checkScrollPosition, delay

      if scrollable() && nearBottom()
        if options.callback() == true
          enqueueNextCheck(options.delay)
      else
        enqueueNextCheck(options.delay)
)(jQuery)

After adding this plugin to your project, you can use it by calling nearBottom on a jQuery object.

yourFunction = ->
  alert "We're near the bottom of the page!"
  true

$(this).nearBottom {
  callback: yourFunction,
  delay: 500,
  pixelsFromBottom: 100
}

I’ve included all of the optional settings above.


comments powered by Disqus

Recent Articles