Last active
August 15, 2018 16:33
-
-
Save silentsilas/a32fc5f6ec56f521002349bec8fb810f to your computer and use it in GitHub Desktop.
A more reliable way to check if device uses touch or mouse.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://blogs.perficientdigital.com/2017/11/21/detecting-the-use-of-a-touch-screen/ | |
// Usage: isTouch().then( (result) ) { | |
// if (result) console.log("Yep, uses touch"); | |
// else console.log("Nope, uses mouse"); | |
//} | |
// Set a variable detecting the existence of touch events | |
var _hasEvents = 'ontouchstart' in window || navigator.msMaxTouchPoints > 0; | |
var _isTouchCached = null; | |
// Default isTouch check | |
export function isTouch() { | |
return new Promise(function (resolve, reject) { | |
if (_isTouchCached != null) { | |
resolve(_isTouchCached); | |
} | |
// If the browser supports touch events | |
if (_hasEvents) { | |
// Add the mouse/touch event listeners | |
_addListeners(resolve, reject); | |
} | |
else { | |
// If the browser doesn't support touch events | |
resolve(false); | |
} | |
}); | |
} | |
// The function to add the mouse/touch event listeners | |
function _addListeners(resolve, reject) { | |
window.touch_promise = resolve; | |
// Add the mouse event listener | |
window.addEventListener('mousemove', _checkForMouse); | |
// Add the touch event listener | |
window.addEventListener('touchstart', _checkForTouch); | |
} | |
function _checkForMouse(e) { | |
// Remove the mouse/touch event listeners | |
_removeListeners(); | |
_isTouchCached = false; | |
e.currentTarget.touch_promise(false); | |
} | |
function _checkForTouch(e) { | |
// Remove the mouse/touch event listeners | |
_removeListeners(); | |
_isTouchCached = true; | |
e.currentTarget.touch_promise(true); | |
} | |
// The function to remove the mouse/touch event listeners | |
function _removeListeners() { | |
// Remove the mouse event listener | |
window.removeEventListener('mousemove', _checkForMouse); | |
// Remove the touch event listener | |
window.removeEventListener('touchstart', _checkForTouch); | |
} | |
export default { isTouch }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment