francoRMM of MediaMonks BA
11/2/2017 - 5:57 PM

Add Swipe events

Detect the device type and add a swipe (with mouse or touch depending on the device) event. The event detect up, down, left and right directions of swipe

// Get information of the user device
const deviceDetector = (function () {
	let ua = navigator.userAgent.toLowerCase();
	const detect = (function (s) {
		if (s === undefined) s = ua;
		else ua = s.toLowerCase();
		if (/(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(ua))
			return 'tablet';
		else if (/(mobi|ipod|phone|blackberry|opera mini|fennec|minimo|symbian|psp|nintendo ds|archos|skyfire|puffin|blazer|bolt|gobrowser|iris|maemo|semc|teashark|uzard)/.test(ua))
			return 'mobile';
		else return 'desktop';
	});
	return {
		device: detect(),
		detect: detect,
		isMobile: detect() !== 'desktop',
		userAgent: ua
	};
}());

// Set the values to startSwipePosition to compare on the swipe
function startSwipe(e) {
	startSwipePosition = {};
	startSwipePosition.x = e.touches ? e.touches[0].clientX : e.clientX;
	startSwipePosition.y = e.touches ? e.touches[0].clientY : e.clientY;
}

// Check where the swipe moved and execute the correct function
const endSwipe = (up, down, left, right) => (e) => {
	if (!startSwipePosition)
		return;

	const swipePosition = {};
	swipePosition.x = e.touches ? e.touches[0].clientX : e.clientX;
	swipePosition.y = e.touches ? e.touches[0].clientY : e.clientY;

	let xDiff = startSwipePosition.x - swipePosition.x;
	let yDiff = startSwipePosition.y - swipePosition.y;

	if (Math.abs(xDiff) > Math.abs(yDiff)) {
		if (xDiff > 0) {
			if (left) left();
		} else {
			if (right) right();
		}
	} else {
		if (yDiff > 0) {
			if (up) up();
		} else {
			if (down) down();
		}
	}

	/* reset values */
	startSwipePosition = null;
};

// Add the swipe functions to the domObj
function addSwipeEvents(domObj, upFun, downFun, leftFun, rightFun) {
	domObj.addEventListener(deviceDetector.isMobile ? 'touchstart' : 'mousedown', startSwipe);
	domObj.addEventListener(deviceDetector.isMobile ? 'touchmove' : 'mouseup', endSwipe(upFun, downFun, leftFun, rightFun));
}