Search code examples
androidipaddom-eventstouch-eventtouches

TouchLeave for DOM element


I want a div element on my page which increases a number on the page while it is pressed. This is fairly easy, but I want this to work on IPad and Android devices as well.

I am using the touchstart event using jQuery bind on the div. Using a setInterval I update the number (I could use calling a setTimeout every time the number is increased, but that is irrelevant). I want the interval cleared when the finger (touch) moves outside the div. Unfortunately touchend is not called until the finger is released from the screen. Mobile safari or webkit do not seem to support touchleave.

So here my question: Any ideas on how to mimic touchleave?


Solution

  • Based on above answer, here's what I do.

    var $this = $('elementselector');
    var fnmove = function (e) {
    e.preventDefault();
    e = e.originalEvent;
    var touch = e.touches[0] || e.changedTouches[0];
        if (!_isInBounds(touch, $this.offset(), $this.outerWidth(), $this.outerHeight())) {
            $this.trigger(touch_leave_event);
            $this.unbind(touch_move_event, fnmove);
        };
    };
    $this.bind(touch_move_event, fnmove);
    

    -- inbounds function

    function _isInBounds(touch, elemposition, width, height) {
        var left = elemposition.left,
            right = left + width,
            top = elemposition.top,
            bottom = top + height,
            touchX = touch.pageX,
            touchY = touch.pageY;
    
        return (touchX > left && touchX < right && touchY > top && touchY < bottom);
    };