Touch Drag

In this example we allow the user to drag a cube around on the screen of the device by listening to the mouse and touch events. The example works on a pc or with a touch device.

Using CSS we define the red square:

index.html.haml
.square {
  height: 100px;
        width: 100px;
        background-color: red;
        position: absolute;
        top: 15px;
        left: 15px;
        color: white;
        text-align: center;
}

For the touch interaction we must bind to the touchstat and touchend events. Once we receive a touchstart event, we start tracking the movements of the finger using the touchmove event.

Note that in certain browsers or devices, it's better to disable the mousedown event when you are sure the user is interacting with a touch device.

index.html.haml
var square = $('.square');

square.on('touchstart', function(e){
  setOffset(e);
  square.on('touchmove', drag);
  //square.off('mousedown');
});
square.on('touchend', function(e) {
  square.off('touchmove');
});

To support the mouse interaction, we listen to the mousedown and mouseup events. We use the mousemove event to track the movement of the mouse and update the position of the cube.

index.html.haml
square.on('mousedown', function(e) {
  setOffset(e);
  square.on('mousemove', drag);
});

square.on('mouseup', function(e) {
   square.off('mousemove');
 });

The main logic for updating the position of the cube is shown below. Note that touch and mouse events have two different ways for retrieving the position of the event. This difference has been captured withing the getPos function.

index.html.haml
var offsetX, offsetY;

function getPos(e) {
 var coord = [];
 if (e.originalEvent.touches && e.originalEvent.touches.length) {
   coord[0] = e.originalEvent.touches[0].clientX;
   coord[1] = e.originalEvent.touches[0].clientY;
        } else
        {
   coord[0] = e.clientX;
   coord[1] = e.clientY;
        }
 return coord;
}

function setOffset(e) {
 var coord = getPos(e);
 offsetX = coord[0] - square.position().left;
 offsetY = coord[1] - square.position().top;
}

function drag(e) {
 var coord = getPos(e);
 square.css('left', coord[0] - offsetX + 'px');
 square.css('top', coord[1] - offsetY + 'px');
        return false;        
}