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’s written in CoffeeScript. If you need javascript, feel free to copy and paste this code into the CoffeeScript parser at http://jashkenas.github.com/coffee-script/.
(($) -> $.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.
- callback is the function to execute when the user scrolls close to the bottom of the page. This function must return a value of true for the plugin to continue to check the user’s scroll position. In other words, if you want to stop the plugin, return false and your callback will not be called again.
- delay is how many milliseconds to wait between each check of the scroll position
pixelsFromBottom is the distance from the bottom of the page that triggers the callback.
I’ll add this to GitHub soon!