Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 370
user1031947 Avatar asked Sep 18 '14 18:09

user1031947


People also ask

How does touchmove work?

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.

What is the use of Touch_move?

The touchmove event is used to execute a script when the user moves the finger across the screen. It works only on touch screen devices and triggers once for every movement and continues to trigger until the finger is released. All HTML elements supported by this event.


1 Answers

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

like image 140
Roamer-1888 Avatar answered Oct 06 '22 00:10

Roamer-1888