Skip to content

Instantly share code, notes, and snippets.

@wjdp
Created July 15, 2016 16:32
Show Gist options
  • Save wjdp/b1ebdb414400a08173288e26a42a801c to your computer and use it in GitHub Desktop.
Save wjdp/b1ebdb414400a08173288e26a42a801c to your computer and use it in GitHub Desktop.
CoffeeScript cosine animated scroll class
class AnimatedScroll
constructor: (scrollEnd, scrollDuration) ->
@scrollStart = window.scrollY
@scrollStep = Math.PI / scrollDuration
@cosParameter = (@scrollStart - scrollEnd) / 2
@scrollEnd = scrollEnd
@scrollDuration = scrollDuration
@scrollCount = 0
@firstTs = null
go: ->
requestAnimationFrame(@step)
step: (ts) =>
if not @firstTs
@firstTs = ts
animationTime = ts - @firstTs
if animationTime <= @scrollDuration
requestAnimationFrame(@step)
scrollMargin = @cosParameter - @cosParameter * Math.cos( animationTime * @scrollStep )
window.scrollTo(0, @scrollStart - scrollMargin)
else
window.scrollTo(0, @scrollEnd)
scrollToAnimated = (pos, duration) ->
as = new AnimatedScroll(pos, duration)
as.go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment