revy
revy

Reputation: 4707

mousedown and mouseup triggered on touch devices

Just curious about the purpose of mousedown and mouseup events since they are triggered also on touch devices. I thought that mousedown and touchstart are mutually exclusive (the former working on desktop while the latter on touch devices) and the same for mouseup and touchend, but it seems this is not the case. A complete touch event triggers all the above events: tested on safari and chrome. Thus to differentiate between a click (mouse) event and a click (touch) event I need to use some kind of function that tells me if this is a touch device or not:

    function isTouchDevice() {
        return 'ontouchstart' in window        // works on most browsers
            || navigator.maxTouchPoints;       // works on IE10/11 and Surface
    }

    myElem.addEventListener("mousedown", () => {
        if (isTouchDevice()) return;
        // do something
    }, false);

    myElem.addEventListener("mouseup", () => {
        if (isTouchDevice()) return;
        // do something
    }, false);

    myElem.addEventListener("touchstart", () => {
        // do something
    }, false);

    myElem.addEventListener("touchend", () => {
        // do something
    }, false);

Do I really need to check if a device is touch or not to discriminate between mouse clicks and touch clicks?

Upvotes: 9

Views: 8304

Answers (2)

Toxiro
Toxiro

Reputation: 612

The correct way to handle this is PointerEvent and pointerType:

targetElement.addEventListener(
  "pointerdown",
  (event) => {
    // Call the appropriate pointer type handler
    switch (event.pointerType) {
      case "mouse":
        process_pointer_mouse(event);
        break;
      case "pen":
        process_pointer_pen(event);
        break;
      case "touch":
        process_pointer_touch(event);
        break;
      default:
        console.log(`pointerType ${event.pointerType} is not supported`);
    }
  },
  false,
);

Upvotes: 4

Devin Fields
Devin Fields

Reputation: 2544

No, you don't and probably shouldn't attempt to test if the device is a touch screen or not. If you wish to stop the other events from triggering, you can use the preventDefault method.

myElem.addEventListener("touchstart", (event) => {
   event.preventDefault(); 
   // do something
}, false);

If you want more in-depth information, you should read this article: Touch and Mouse

Upvotes: 5

Related Questions