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?
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.
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.
To summarise, you appear to want :
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With