JavaScript
Article

jQuery Add Drag/Touch Support for iPad

By Sam Deering

jQuery code snippet to apply Drag/Touch Support for the iPad and devices with touch support. Could be particularly useful with jQuery UI draggable and floating objects.

//iPAD Support
  $.fn.addTouch = function(){
    this.each(function(i,el){
      $(el).bind('touchstart touchmove touchend touchcancel',function(){
        //we pass the original event object because the jQuery event
        //object is normalized to w3c specs and does not provide the TouchList
        handleTouch(event);
      });
    });

    var handleTouch = function(event)
    {
      var touches = event.changedTouches,
              first = touches[0],
              type = '';

      switch(event.type)
      {
        case 'touchstart':
          type = 'mousedown';
          break;

        case 'touchmove':
          type = 'mousemove';
          event.preventDefault();
          break;

        case 'touchend':
          type = 'mouseup';
          break;

        default:
          return;
      }

      var simulatedEvent = document.createEvent('MouseEvent');
      simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0/*left*/, null);
      first.target.dispatchEvent(simulatedEvent);
    };
  };
  • Pingback: 10+ jQuery iPad Plugins | jQuery4u()

  • http://www.websitetemplates.org/ Stacy Summers

    wow! thanks for sharing

    • http://jquery4u.com/ jQuery4u

      your welcome Stacy!

  • Lisa Savy

    Very nice … do you have any drag/drop routines that will work on both iPad and normal computer with mouse?

  • Pingback: jQuery-сниппеты и плагины для iPad()

  • Ian Baylis

    Do we place the code in the file and then reference the file? How would we reference this snippet in the code?

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.