I am trying to implement swipe back and left on the mouse trackpad for my app. I tried using scroll but I think because I have overflow set to hidden for my app (and it is necessary), nothing happens. This is the code I have:
window.addEventListener('wheel', function(event) {
event.preventDefault();
let deltaX = Math.sign(event.deltaX);
// Check for pinch/zoom
if (event.ctrlKey) {
if (event.wheelDelta > 0) {
// increase zoom
} else {
// decrease zoom
}
// when deltaX is 1 or -1, a swipe action has taken place
} else if (deltaX == -1) {
// go forward
goForward();
} else if (deltaX == 1) {
// go back
goBack();
}
}
Now, this sort of works but because a swipe goes on and on, the goForward and goBack functions run again and again. I would like for them to run only once. I would also like to take into account the fact that a user can swipe again and again. Any help? Also, is it possible to somehow call scroll with overflow set to hidden as this would make my life a lot easier? Many Thanks
EDIT, QUESTION IS ANSWERED
Here is the function I used
// objects for mouse wheel events (pinchzoom, swipe)
let lastWheelTime = 0;
let callSwipeFunction = false;
let wheelStartTime = 0;
let enableSwipe = true;
window.addEventListener('wheel', function(event) {
event.preventDefault();
event.stopPropagation();
let deltaX = Math.sign(event.deltaX);
// when a swipe is made Math.sign(deltaX) goes from 1 to -0 to 1 if it is a backward swipe i.e from right to left and from -1 to -0 to -1 if it is a forward swipe
// when it is -0, set the callSwipeFunction to true. -0 is always inbetween
if ( deltaX == -0) {
callSwipeFunction = true;
}
// during a swipe, event.deltaY is always -0 because a swipe is done in a straightish line
if (event.deltaY != -0) { callSwipeFunction = false; }
// check if swipes can be enabled
if (event.timeStamp > (lastWheelTime + 350)) {
enableSwipe = true;
}
// if callSwipeFunction is true, call nextImage. then set it back to false until a new swipe is made
// deltaX = 1 means we are swiping to the right. go back one image
// deltaX = -1 means we are swiping to the left. go back one image
if ((deltaX == -1 || deltaX == 1) && callSwipeFunction && enableSwipe) {
// nextImage is the function we are running when a swipe is done
nextImage( (deltaX * -1) );
// reset variables
callSwipeFunction = false;
enableSwipe = false;
lastWheelTime = event.timeStamp;
}
// clean up
window.onwheel = null;
//window.onwheel = function() { return false; };
// return false
return false;
}, {passive: false});