Skip to content

Instantly share code, notes, and snippets.

@adamloving
Created January 29, 2012 19:45
Show Gist options
  • Save adamloving/1700332 to your computer and use it in GitHub Desktop.
Save adamloving/1700332 to your computer and use it in GitHub Desktop.
Webkit (iPhone Safari) swipe event handler
# This is a translation of http://rabblerule.blogspot.com/2009/08/detecting-swipe-in-webkit.html
class SwipeListener
constructor: (@el, @handler) ->
@el.addEventListener('touchstart', @onTouchStart, false);
@startX = @startY = @direction = null
cancelTouch: () ->
@el.removeEventListener('touchmove', @onTouchMove)
@el.removeEventListener('touchend', @onTouchEnd)
@startX = null
@startY = null
@direction = null
onTouchMove: (e) =>
if e.touches.length > 1
@cancelTouch()
else
@dx = e.touches[0].pageX - @startX
@dy = e.touches[0].pageY - @startY
if @direction == null
@direction = @dx
e.preventDefault()
else if @direction < 0 && @dx > 0 || @direction > 0 && @dx < 0 || Math.abs(@dy) > 15
@cancelTouch()
onTouchEnd: (e) =>
@cancelTouch()
if Math.abs(@dx) > 30
if @dx > 0 then direction = 'right' else direction = 'left'
@handler(target: @el, direction: direction)
onTouchStart: (e) =>
if (e.touches.length == 1)
@startX = e.touches[0].pageX
@startY = e.touches[0].pageY
@el.addEventListener('touchmove', @onTouchMove, false);
@el.addEventListener('touchend', @onTouchEnd, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment