Search code examples
javascriptjquerytouchtouchscreen

How to implment touch funcationality on a PC running Windows using Jquery/Javascript?


I have implemented the touch functionality to my website using these code and it works fine for iPad/iPhone.

// registering touch events
function initTouchEvents() {

    // if a device is a touch device
    if (window.Touch) {
        document.addEventListener("touchstart", touchHandler, true);
        document.addEventListener("touchmove", touchHandler, true);
        document.addEventListener("touchend", touchHandler, true);
        document.addEventListener("touchcancel", touchHandler, true);
    }
}

// making items sortable in touch screen devices
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;
    }
    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);

    if (event.type == "touchmove") {

        event.preventDefault();
    }
}

But when I tested my website on touch screen PC, it doesn't run and I found out that the window.Touch only run for iPhone/iPad. And I also tried various other events like typeof(window.ontouchstart != 'undefined') and ('ontouchstart' in window || typeof TouchEvent != "undefined") but it doesn't detect that it's touch screen and doesn't register the event for touch movement.

What I am asking here is for an event in javascript that can detect all the touch devices (that IOS/Android/Windows/OSX) and run register the events.


Solution

  • Phantom Limb makes desktop browsers simulate touch events

    https://github.com/brian-c/phantom-limb