Created
October 24, 2012 10:19
-
-
Save mbernson/3945339 to your computer and use it in GitHub Desktop.
Javascript touch/swipe example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* In this example, `panelElement` references to some DOM object, | |
* with the open, close and toggle methods to show/hide it. | |
*/ | |
// This function opens or closes our panel, according to the swipe coordinates | |
panelElement.performSwipe = function(swipeStart, swipeEnd) { | |
// In case of a short swipe, just toggle the panel. | |
if (Math.abs(start - end) < 16) { | |
this.toggle(); | |
return; | |
} | |
// Open or close the panel, depending on the direction of the swipe | |
if (start < end) this.open(); | |
else if (start > end) this.close(); | |
} | |
// I'm caching the swipe start and end coordinates here, | |
// since the start and end are separate events. | |
var cache.swipeData = {}; | |
// This listener moves the element along with your finger when it's touching | |
panelTouchArea.addEventListener ('touchmove', function(event) { | |
event.preventDefault(); | |
var touch = event.touches[0]; | |
panelElement.moveTo(touch.pageX); | |
}, true); | |
// We capture the swipe's starting point here. | |
panelTouchArea.addEventListener('touchstart', function (event) { | |
event.preventDefault(); | |
var touch = event.changedTouches[0]; | |
cache.swipeData.start = touch.pageX; | |
}, true); | |
// When the swipe ends, capture its coordinates and respond to it. | |
panelTouchArea.addEventListener('touchend', function (event) { | |
event.preventDefault(); | |
var touch = event.changedTouches[0]; | |
cache.swipeData.end = touch.pageX; | |
// Order the element to perform the swipe. | |
panelElement.performSwipe(cache.swipeData.start, cache.swipeData.end); | |
}, true); | |
// For compatibility, we support a click event to open the panel as well. | |
panelTouchArea.addEventListener('click', function () { | |
panelElement.toggle(); | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment