Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if click was triggered by touch in modern browsers

This question is an update to this one, but for modern browsers. (Unfortunately the answers here are outdated and/or not in vanilla JavaScript). Essentially I want to perform a simple test to detect if a click event was triggered by touch or mouse input.

The only answer in the aforementioned question that is foolproof and still works is to use the event.pointerType property. However, event.pointerType seems to only be defined in Chrome for the click event.

While I could use pointer-events (for instance pointerup), for which event.pointerType is defined for all browsers, pointerup behaves differently than click and is more similar to mouseup. In other words it does not register only true clicks, but also fires if the pointer was dragged around or started on another element.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For this reason, I would like to get this to work with regular click events. If anyone knows how I can reliably detect the input method it would be greatly appreciated.

>Solution :

A solution could be, first have a flag to check if get touched or not let’s call it isTouched, this flag is false by default, and create an event listener on the touchstart event and once it get triggered it will turn isTouched to be true, also create another event listener for click and inside it conditionally check if isTouched is true, then reset the isTouched to be false, if it is with false, then there wasn’t a touch event triggered, so it is just a click event.

let isTouched = false;
const testButton = document.getElementById('test');

testButton.addEventListener('touchstart', function(e) {
  isTouched = true;
});


testButton.addEventListener('click', function(e) {
  if (isTouched) {
    alert('Triggered by touch');
    isTouched = false;
  } else {
    alert('Triggered by mouse click');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button id="test">Test</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading