Skip to content

Instantly share code, notes, and snippets.

@HashNuke
Last active December 21, 2015 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HashNuke/6331729 to your computer and use it in GitHub Desktop.
Save HashNuke/6331729 to your computer and use it in GitHub Desktop.
Autoscroll implementation in CoffeeScript. From my latest hobby project. If the user is reading history that's way behind, then do not scroll to the latest message. If the user is reading history that's less than 4 lines away from the latest message, then scroll to the latest message.
# My markup looks like this
#
# <div class="activities">
# <div class="activities-inner-wrapper">
# <div class="activity">something here</div>
# <div class="activity">another thing here</div>
# <div class="activity">Wowowowowwo</div>
# </div>
# </div>
#
# WARNING: Just copy pasting this might not work.
# I extracted this out of my coffeescript class, so you might need to change function references
# This just scrolls to the latest message; Shouldn't directly be called.
scrollToRecentActivity = ->
# adding 100 just to satisfy my paranoia
$('.activities').scrollTop( $('.activities-inner-wrapper').prop('scrollHeight') + 100 )
scrollToRecentActivityIfNecessary = ->
# this is the size of the container that's got the scrollbar
viewableHeight = $('.activities').height()
# this is the height of the wrapper that has all the ".activity" elements.
# this wrapper is inside the container
# and it's height might be greater than that of the container, hidden by scroll
contentHeight = $('.activities-inner-wrapper').height()
# this is the stuff that's already been scrolled
# OR stuff that's hidden in the top because we scrolled to the bottom
coveredHeight = $('.activities').scrollTop()
# stuff which we haven't scrolled to yet
# OR stuff that got hidden in the bottom because we scrolled to the top
bottomHiddenContentSize = contentHeight - (coveredHeight + viewableHeight)
# Do not bother if bottomHiddenContentSize is negative.
# It will be negative if the activities are less very few and can be viewed without scroll
# Available only on some browsers; so we default to 1 if it isn't available
# On iPad Retina it'll be 2. Some devices have 1.5. Most devices have 1
devicePixelRatio = window.devicePixelRatio || 1
thresholdLines = 4
# Assume that 16px == 1em; Multiple that with devicePixelRatio
# And if the scrolled lines are less than threshold number of lines, only then scroll
# because then the user is very close to the recent message
# This way he can also read the history happily.
if (bottomHiddenContentSize/(16 * devicePixelRatio) < thresholdLines
scrollToRecentActivity()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment