Skip to content

Instantly share code, notes, and snippets.

@adamcbrewer
Last active October 22, 2021 20:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamcbrewer/4994466 to your computer and use it in GitHub Desktop.
Save adamcbrewer/4994466 to your computer and use it in GitHub Desktop.
JS: Detect for supported 'touchstart' events.
/**
* 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
});
@adamcbrewer
Copy link
Author

Have provided an alternate choice for the touch event type. Should hopefully solve issues with clicks firing when the user tries to scroll.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment