Skip to content

Instantly share code, notes, and snippets.

@kanso-git
Forked from brandondurham/swipeFunc.js
Created June 20, 2016 20:21
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 kanso-git/e47048721765232fb28f06be7c5b408d to your computer and use it in GitHub Desktop.
Save kanso-git/e47048721765232fb28f06be7c5b408d to your computer and use it in GitHub Desktop.
Updated swipe script for React
import React, { Component } from 'react';
import update from 'react-addons-update';
export default class App extends Component {
state = {
touches: {
touchstart: {
x: -1,
y: -1
},
touchmove: {
x: -1,
y: -1
},
distance: {
x: -1,
y: -1
},
touchend: false,
direction: null
}
}
componentDidMount() {
window.addEventListener('touchstart', this.touchHandler, false);
window.addEventListener('touchmove', this.touchHandler, false);
window.addEventListener('touchend', this.touchHandler, false);
}
componentDidUnmount() {
window.removeEventListener('touchstart', this.touchHandler, false);
window.removeEventListener('touchmove', this.touchHandler, false);
window.removeEventListener('touchend', this.touchHandler, false);
}
/**
* Difference
* Utility function to calculate the number of points between two numbers.
* @param {number} num1
* @param {number} num2
* @return {number}
*/
_difference = (num1, num2) => {
return (num1 > num2) ? num1 - num2 : num2 - num1;
}
touchHandler = (event) => {
let touch;
if (typeof event !== 'undefined') {
if (typeof event.touches !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart':
case 'touchmove': {
const newState = update(this.state, {
touches: {
[event.type]: {
x: { $set: touch.pageX },
y: { $set: touch.pageY }
},
touchend: { $set: false }
}
});
this.setState(newState);
break;
}
case 'touchend': {
if (
this.state.touches.touchstart.y > -1 &&
this.state.touches.touchmove.y > -1
) {
const newState = update(this.state, {
touches: {
direction: { $set: this.state.touches.touchstart.y < this.state.touches.touchmove.y ? 'down' : 'up' },
distance: {
x: { $set: this._difference(this.state.touches.touchstart.x, this.state.touches.touchmove.x) },
y: { $set: this._difference(this.state.touches.touchstart.y, this.state.touches.touchmove.y) }
},
[event.type]: { $set: true }
}
});
this.setState(newState);
}
break;
}
default:
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment