Subscribe to Blog via Email

JavaScript Drag Events on iPhone and Other Touch Based Devices

For quite a while this week, we were trying to work on dragging JavaScript elements on iPad and other devices with touch input. For our case, we already had jQuery included in our codes, hence we were tempted to use the touchmove event and depend on native jQuery to do the rest.

Things turned out to be a bit trickier. After implementation, it struck us that with jQuery bound events, event.pageX and other related mouse coordinate attributes would not work. Add to that, we were using the jQuery.event.drag plugin by ThreeDubsmedia to seal of the dirty job of drag-related coding.

Armed with the above two problems, we started to do what we thought would be the fastest solution – modify the jQuery.event.drag plugin for a graceful upscale!

Last night, I sat down with the codes and woke up this morning to have the original plugin modified to work as I wanted it to. The original code was written in a well structured manner. This allowed the changes to be done in without affecting much of the code pattern.

The places where the original code responded to mousedown, mousemove and mouseup events were respectively replaced by touchstart, touchmove and touchend events.

Also, the necessary codes needed to check prevention of viewport scrolling were added along with codes to copy the touch coordinates to mouse-pointer coordinates.

If one is already using the original plugin, simply replacing the same with the downloadable script in this page would make the drag events on a page to work perfectly on touch inputs. The existing dragstart, drag and dragend events will become functional once the original code is replaced by the code in this plugin.

Even the event.pageX, event.layerX and other related attributes are fixed to match the last touched finger.