Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript equivalent of 'mouseleave' for touch interactions

Prelim caveat: I am very new to js and have mainly gotten by through doing web searches for examples/tutorials.

I am writing js which should run both on web and on mobile devices (e.g. iPad).

We have a library to help abstract away the differences between mouse and touch:

if (navigator.userAgent.search('Mobile') > 0) {
  window.FLAGS = {
    start: 'touchstart',
    end: 'touchend',
    move: 'touchmove',
    click: 'click',
    touchScreen: true
  };
} else {
  window.FLAGS = {
    start: 'mousedown',
    end: 'mouseup',
    move: 'mousemove',
    click: 'click',
    touchScreen: false
  };
}

Then in code you can do things like:

widget.view.bind(FLAGS.start, function(e) {

I am trying to find a touch equivalent for mouseleave so I can do a similar trick.

I can imagine ways to catch a leave event by tracking the position on move and comparing that to bounding box of widget in question, but I'm hoping there's a little one-liner like the touchstart/mousedown relationship.

like image 204
Doug Banks Avatar asked Apr 21 '11 18:04

Doug Banks


People also ask

Does MouseEnter work on mobile?

Mobile devices don't have a mouse. So technically you can't hover in them. Some events work on all devices even ones they're not built for. The MouseLeave works on mobile however the MouseEnter was not designed to work on mobile as it does not have a mouse.

Does touchstart work on desktop?

The touchstart event occurs when the user touches an element. Note: The touchstart event will only work on devices with a touch screen.

What is the use of Touch_move?

Definition and Usage The touchmove event occurs when the user moves the finger across the screen. The touchmove event will be triggered once for each movement, and will continue to be triggered until the finger is released. Note: The touchmove event will only work on devices with a touch screen.


1 Answers

It's been suggested, but not implemented AFAIK: http://www.quirksmode.org/mobile/advisoryTouch.html

Something like this might work (writing it from top of my head, untested):

var element;
document.addEventListener('touchstart', function(event) {
    event.preventDefault();
    var touch = event.touches[0];
    element = document.elementFromPoint(touch.pageX,touch.pageY);
}, false);

document.addEventListener('touchmove', function(event) {
    event.preventDefault();
    var touch = event.touches[0];
    if (element !== document.elementFromPoint(touch.pageX,touch.pageY)) {
        touchleave();
    }
}, false);

function touchleave() { 
    console.log ("You're not touching the element anymore");
}
like image 50
Aleadam Avatar answered Sep 19 '22 12:09

Aleadam