How to bind ‘touchstart’ and ‘click’ events but not respond to both ?
The touchstart event occurs when the user touches an element. But a click event is fired when the user clicks an element.
Usually, both the touchstart and click events are fired in the very same click in the touch and click enabled devices. So, in this case, if the browser fires both touch and mouse events because of single user input, the browser must fire a touchstart before any mouse events.
There are two popular ways of solving this issue.
- Use of the preventDefault() or stopPropagation() method.
- Using a variable to check whether it is a “touchstart” or a “click” event.
Use of the preventDefault() or stopPropagation() method: This method prevents the event handler from responding to both touchstart and clicks events. If an application does not want mouse events fired on a specific touch target element, the element’s touch event handlers should call preventDefault() or stopPropagation() and no additional mouse events will be dispatched.
Output when a touchstart event is triggerrd
Here a touchstart event is triggered After triggering an event
However, this also prevents other default browser behavior (like scrolling) – although usually you’re handling the touch event entirely in your handler, and you have to disable the default actions.
Also, when a user taps on an element in a web page on a mobile device, pages that haven’t been designed for mobile interaction have a delay of at least 300 milliseconds between the touchstart event and the processing of mouse events (mousedown). So, a line of HTML code has to be added depicting that the page doesn’t need zooming.
<meta name="viewport" content="width=device-width, user-scalable=no">
Using a variable to check whether it is a “touchstart” or a “click” event:
click event is triggered After triggering an event