From afb1f6d116e3e2085230c96dd04f035255427083 Mon Sep 17 00:00:00 2001 From: Gerome Matilla Date: Thu, 4 Jun 2020 12:52:56 +0800 Subject: [PATCH] add mobile swipe event js --- index.html | 2 ++ js/mobile-swipe-event.js | 61 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 js/mobile-swipe-event.js diff --git a/index.html b/index.html index 3952fba..d700674 100644 --- a/index.html +++ b/index.html @@ -231,5 +231,7 @@ + + \ No newline at end of file diff --git a/js/mobile-swipe-event.js b/js/mobile-swipe-event.js new file mode 100644 index 0000000..f11a73b --- /dev/null +++ b/js/mobile-swipe-event.js @@ -0,0 +1,61 @@ +const swipeEvent = (elementID, callback) => { + + var el = document.getElementById(elementID); + var dir; + + el.addEventListener( + 'touchstart', + (event) => { + // event.preventDefault(); + xDown = event.touches[0].clientX; + yDown = event.touches[0].clientY; + }, + { passive: true } + ); + + el.addEventListener( + 'touchmove', + (event) => { + // event.preventDefault(); + if ( ! xDown || ! yDown ) { + return; + } + + var xUp = event.touches[0].clientX; + var yUp = event.touches[0].clientY; + var xDiff = xDown - xUp; + var yDiff = yDown - yUp; + + if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) { + if ( xDiff > 0 ) { + // Left Swipe + dir = 'left' + } else { + // Right Swipe + dir = 'right'; + } + } else { + + if ( yDiff > 0 ) { + // Up Swipe + dir = 'up'; + } else { + // Down Swipe + dir = 'down'; + } + } + + /* Reset values */ + xDown = null; + yDown = null; + + if (dir !== ""){ + if (typeof callback == "function") { + callback(el, dir); + } + } + + }, + { passive: true } + ); +} \ No newline at end of file