How can I catch touchmove events on an element that is added to the DOM after my finger is already on the screen?

user1031947 picture user1031947 · Sep 18, 2014 · Viewed 24.9k times · Source

I am working on a Javascript / html5 project for iPad.

I need to be able to catch touchmove events on an element that does not get added to the DOM until after a touchstart event has fired (i.e. until after a person has put their finger on the screen.)

I have tried simulating a touchstart event and firing it programatically...

$( "#container" ).append( element );
element.on( "touchmove", doStuff );
var ev = $.Event( "touchstart" );
element.trigger( ev );

...however this does not work. The only way I can get doStuff to start firing is to lift my finger and then touch the screen again, triggering a second touchstart event.

How can I catch touchmove events on an element that is added to the DOM after my finger is already on the screen?

Answer

Roamer-1888 picture Roamer-1888 · Sep 19, 2014

To summarise, you appear to want :

  • on touchstart: to display and position a styled div element.
  • on touchmove: to drag the element without releasing and re-pressing the mouse button.

If this interpretation is correct, then the answer is to to handle touchmove events on the same element that was originally clicked on - namely the "body" element. It is not necessary to handle touchmove events of the element you want to drag (the added element).

There must be many ways to write the code. Here's one, which is probably not exactly what you want (chiefly in the positioning maths) but should be simple to adapt :

var $element = $("<div class='element' />");

$("body").on({
    'touchstart mousedown': function (e) {
        $element.appendTo("body");
        $(this).on('touchmove mousemove', move);
        move(e);//you could do `$(this).trigger('touchmove', e)` but a conventional function call keeps `move` simple.
    },
    'touchend mouseup': function (e) {
        $(this).off('touchmove mousemove');
    }
});

function move(e) {
    $element.css({
        left: (e.pageX - 10) + 'px',
        top: (e.pageY - 10) + 'px',
        cursor: 'pointer'
    });
}

mousedown/mousemove/mouseup allow for desktop testing and can be removed for touch device usage.

DEMO