Skip to content

Instantly share code, notes, and snippets.

@wbobeirne
Created January 28, 2014 01:35
Show Gist options
  • Save wbobeirne/8660911 to your computer and use it in GitHub Desktop.
Save wbobeirne/8660911 to your computer and use it in GitHub Desktop.
# Provides functions that help with scrolling
# -----------------------------------------------------------------------------
Ok.ScrollHelpers = {
# Check if an element has a scrollbar.
checkScroll: (element, dir) ->
if dir == 'horizontal'
# Half pixels on innerWidth get rounded down. Better way to handle this?
return element.prop('scrollWidth') > (element.innerWidth() + 1)
else
return element.prop('scrollHeight') > element.innerHeight()
# Prevent body from scrolling when you reach the top / bottom of an element
preventOverscroll: (element) ->
if typeof element == 'string' then element = $('#' + element)
element.on('mousewheel', (e, delta) ->
$element = $(this)
if ScrollHelpers.checkScroll($element)
scrollTop = $element.scrollTop()
# Prevent top scroll
if delta > 0 && scrollTop == 0
e.preventDefault()
# Prevent bottom scroll
else if delta < 0 && (scrollTop == $element.prop('scrollHeight') - $element.innerHeight())
e.preventDefault()
)
# Simple animated scroll.
# Position - position of where to scroll in px from top.
# Speed - speed to scroll in ms. Blank or 0 for instant jump.
scrollTo: (position, speed) ->
if speed
$('body, html, window, document').animate({
scrollTop: position
}, speed);
else
$(window).scrollTop(position)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment