By CHI WAI LAU

Supporting Mouse Events on Mobile Safari

Mobile Safari does a good job for making websites work seamlessly in a mouse-free environment. In general, it is pretty painless for both users and developers. For example, if you tap on something, the event would automatically be interpreted and handled as a mouse click. However, not everything is automatic; if the websites have any interactions involving mousedown, mousemove, and mouseup, they will not work well on Mobile Safari.

To support those interactions everywhere, developers need to take care of both touch and mouse events. One approach is to have additional event listeners for touch, but it gets tedious and ugly very quickly. A more elegant approach is to implement a global adapter that automatically map mouse events to touch events. Here’s how I did it with Scott’s help using MooTools:

(function() {
  try {
    document.createEvent("TouchEvent");
  } catch(e) {
    return;
  }

  ['touchstart', 'touchmove', 'touchend'].each(function(type){
      Element.NativeEvents[type] = 2;
  });

  var mapping = {
    'mousedown': 'touchstart',
    'mousemove': 'touchmove',
    'mouseup': 'touchend'
  };

  var condition = function(event) {
    var touch = event.event.changedTouches[0];
    event.page = {
      x: touch.pageX,
      y: touch.pageY
    };
    return true;
  };

  for (var e in mapping) {
    Element.Events[e] = {
      base: mapping[e],
      condition: condition
    };
  }
})();

The code above is kept at Github. You can follow it for improvements or bug fixes.

Touch is the new mouse! To fully embrace touch, you should definitely check out the Safari Web Content Guide and learn more about the new touch events.