Last active
October 22, 2021 20:29
-
-
Save adamcbrewer/4994466 to your computer and use it in GitHub Desktop.
JS: Detect for supported 'touchstart' events.
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
/** | |
* Using default click events in touch-supported devices | |
* incurs a delay (in order to determine if the user is performing a gesture). | |
* | |
* Detecting for touchstart events using the foloowing, we can replace the default 'clicks' | |
* for touch events, making a snappier experience for mobile/touch devices. | |
* Use wisely as this could prevent some gestures from happening. If there are scrolling | |
* issues try swap out 'touchstart' for 'touchend' | |
* | |
*/ | |
var clickEventType = ('ontouchstart' in window ? 'touchend' : 'click'); | |
// This is the best method though, so use this if where possible | |
// source: https://hacks.mozilla.org/2013/04/detecting-touch-its-the-why-not-the-how/ | |
element.addEventListener('touchend', function(e) { | |
// prevent delay and simulated mouse events | |
e.preventDefault(); | |
// trigger the actual behavior we bound to the 'click' event | |
e.target.click(); | |
}) | |
element.addEventListener('click', function() { | |
// actual functionality | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have provided an alternate choice for the touch event type. Should hopefully solve issues with clicks firing when the user tries to scroll.