Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active September 2, 2019 09:05
Show Gist options
  • Save LeanSeverino1022/a31526b1873639c8ccfdf24fa40dfb33 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/a31526b1873639c8ccfdf24fa40dfb33 to your computer and use it in GitHub Desktop.
detect if user is using touch device #vanillajs
//the FAV part is the approach I'd like to use. I've researched a lot about this and this seems to be a great choice. see https://codeburst.io/the-only-way-to-detect-touch-with-javascript-7791a3346685
// We really just want to know if the user is using their fingers to interact with our site.
// #1 basic logic
window.addEventListener('touchstart', function() {
//the user touched the screen
});
//#2 FAV: a more detailed example
window.addEventListener('touchstart', function onFirstTouch() {
// we could use a class
document.body.classList.add('user-is-touching');
// or set some global variable
window.USER_IS_TOUCHING = true; //I like this
// or set your app's state however you normally would
myFrameworkOfChoice.dispatchEvent('USER_IS_TOUCHING', true);
// we only need to know once that a human touched the screen, so we can stop listening now
window.removeEventListener('touchstart', onFirstTouch, false);
}, false);
// #3 another method maybe?
try {
document.createEvent("TouchEvent");
alert(true);
}
catch (e) {
alert(false);
}
// #4 and another one?
function checkTouchDevice() {
return 'ontouchstart' in document.documentElement;
}
Here, you can also use it to detect mobile or desktop, like the following:
if (checkTouchDevice()) {
// Mobile device
} else {
// Desktop
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment