10

When working with desktop browsers you can use the JavaScript event mouseout.

When using a mobile browser you have only touch events. Tried to find an equivalent for the mouseout event. It turns out that touchend event is not the equivalent because it will only fire when the touch ends in the element where the touch handler is registered.

Is there a touch equivalent to the mouseout event?

Michael
  • 32,527
  • 49
  • 210
  • 370
  • Possible Duplicate? [Prefered Alternative to OnMouseOver for touch](http://stackoverflow.com/questions/4550427/prefered-alternative-to-onmouseover-for-touch) – Izzy Jul 22 '14 at 14:00

2 Answers2

9

See this article from MDN

Specifically, touchend

When the user lifts a finger off the surface, a touchend event is sent.

Although, you may also want to refer to touchcancel

If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the touchcancel event is sent

SW4
  • 69,876
  • 20
  • 132
  • 137
  • `touchend` and **`touchcancel`** (ie, not `touchleave`)? – dylnmc Jul 06 '18 at 19:35
  • 1
    @dylnmc - you are correct, the original answer was posted before the spec had progressed, touchleave is still experimental and likely due for deprecation, touchcancel is an eligible event (as reflected by the updates in the MDN ref) - good spot! – SW4 Jul 10 '18 at 21:54
4

If you are looking for a way to imitate the “mouseout” event, I made this implementation within the “touchmove”- and “touchend” event.

element.addEventListener("touchmove", (e) => {
 if (this.isTouchEventWithElement(e)) return;
 // PERFORM MOUSEOUT ACTION
});


element.addEventListener("touchend", (e) => {
 if (this.isTouchEventWithElement(e)) return;
 // PERFORM MOUSEOUT ACTION
});


isTouchEventWithElement(e: TouchEvent): boolean {
 const element = this.getElement();
 const item = e.changedTouches.item(0);
 if (element === null || item === null) return false;
 return element.getBoundingClientRect().right > item.clientX &&
     element.getBoundingClientRect().left < item.clientX &&
     element.getBoundingClientRect().top < item.clientY &&
     element.getBoundingClientRect().bottom > item.clientY;
}

Hope it helps.

Inspired by: http://www.javascriptkit.com/javatutors/touchevents.shtml