Skip to content

Instantly share code, notes, and snippets.

@patrixd
Last active August 29, 2015 14:10
Show Gist options
  • Save patrixd/5992bb37f005ec3bd242 to your computer and use it in GitHub Desktop.
Save patrixd/5992bb37f005ec3bd242 to your computer and use it in GitHub Desktop.
MouseWheel Event Crossbrowser
# The better is to use the next: https://github.com/jquery/jquery-mousewheel
$('body').on('mousewheel', onMouseWheel);
onMouseWheel = (e) ->
scrollDistance = e.deltaY * e.deltaFactor
wHeight = $(window).innerHeight()
newScrollTop = scrollDistance * -1 + $('body').scrollTop()
#Example of use, automatic scrolldown when the next slide is in the middle it scrolls down automatically
clearTimeout(window._scrollTimer)
window._scrollTimer = setTimeout(() ->
currentSlide = getCurrentSlide()
if scrollDistance * -1 > 0 # Down
newSlide = getNextSlide(currentSlide)
if !newSlide
return
offset = slidesPosition[newSlide + "Pixels"]
if offset < newScrollTop || offset > newScrollTop + wHeight
return
animateScroll(offset, 300)
, 500)
getCurrentSlide = () ->
currentSlide = null
currentTop = $('body').scrollTop()
for i in [0...slides.length]
slide = slides[i]
slideTop = slidesPosition[slide + "Pixels"]
if currentTop == slideTop || (currentTop > slideTop && currentTop < slidesPosition[slides[i+1] + "Pixels"])
currentSlide = slide
break
return if currentSlide then currentSlide else slides[slides.length - 1]
getPreviousSlide = (name) ->
previousSlide = null
$slides = $('.slide')
for i in [0...$slides.length]
$slide = $slides.eq(i)
if $slide.data('name') == name && i > 0
previousSlide = $slides.eq(i-1).data('name')
break
previousSlide
getNextSlide = (name) ->
nextSlide = null
$slides = $('.slide')
for i in [0...$slides.length]
$slide = $slides.eq(i)
if $slide.data('name') == name && $slides.length > i+1
nextSlide = $slides.eq(i+1).data('name')
break
nextSlide
window.getMouseWheelEventName = () ->
if 'onwheel' in document
'wheel'
else if 'onmousewheel' in document
'mousewheel'
else
'DOMMouseScroll'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment