javascriptdom-eventstouchscreen

JavaScript mapping touch events to mouse events


I'm using the YUI slider that operates with mouse move events. I want to make it respond to touchmove events (iPhone and Android). How can I produce a mouse move event when a touchmove event occurs? I'm hoping that just by adding some script at the top that touchmove events will get mapped to the mouse move events and I won't have to change anything with the slider.


Solution

  • I am sure this is what you want:

    function touchHandler(event)
    {
        var touches = event.changedTouches,
            first = touches[0],
            type = "";
        switch(event.type)
        {
            case "touchstart": type = "mousedown"; break;
            case "touchmove":  type = "mousemove"; break;        
            case "touchend":   type = "mouseup";   break;
            default:           return;
        }
    
        // initMouseEvent(type, canBubble, cancelable, view, clickCount, 
        //                screenX, screenY, clientX, clientY, ctrlKey, 
        //                altKey, shiftKey, metaKey, button, relatedTarget);
    
        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);
        event.preventDefault();
    }
    
    function init() 
    {
        document.addEventListener("touchstart", touchHandler, true);
        document.addEventListener("touchmove", touchHandler, true);
        document.addEventListener("touchend", touchHandler, true);
        document.addEventListener("touchcancel", touchHandler, true);    
    }
    

    I've captured the touch events and then manually fired my own mouse events to match. Although the code isn't particularly general purpose as is, it should be trivial to adapt to most existing drag and drop libraries, and probably most existing mouse event code. Hopefully this idea will come in handy to people developing web applications for the iPhone.

    Update:

    In posting this, I noticed that calling preventDefault on all touch events will prevent links from working properly. The main reason to call preventDefault at all is to stop the phone from scrolling, and you can do that by calling it only on the touchmove callback. The only downside to doing it this way is that the iPhone will sometimes display its hover popup over the drag origin. If I discover a way to prevent that, I'll update this post.

    Second Update:

    I've found the CSS property to turn off the callout: -webkit-touch-callout.