Skip to content

Instantly share code, notes, and snippets.

@mbernson
Created October 24, 2012 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbernson/3945339 to your computer and use it in GitHub Desktop.
Save mbernson/3945339 to your computer and use it in GitHub Desktop.
Javascript touch/swipe example
/*
* 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