Touch an Mouse Events Javascript

Touch an Mouse Events Javascript

by shapeshifta

HTML

<p>Touch the area and see the log</p>
<div id="touchtest"></div>
<div id="log"></div>

CSS

#touchtest {
    width: 100%;
    height: 500px;
    border: 1px solid green;
    overflow: auto;
}
#log {
    width: 80%;
    height: 500px;
    border: 1px solid #ccc;
    overflow: auto;
}

JavaScript

$(function () {
    var select = document.getElementById('touchtest');
    var log = function (msg) {
        $("<div>").text(msg).prependTo($("#log"));
        console.log(msg);
    };
    var logtouch = function (evtype, t) {
        log(evtype + " " + t.identifier + ": (" + t.pageX + "," + t.pageY + ") force=" + t.webkitForce + " size=" + t.webkitRadiusX + " x " + t.webkitRadiusY + " < " + t.webkitRotationAngle + "deg");
    }

    var mouseIsDown = false;

    select.addEventListener("pointerover", function () {
        mouseIsDown = true;
        log("pointerover");
    }, true);

    select.addEventListener("pointerdown", function () {
        mouseIsDown = true;
        log("pointerdown");
    }, true);

    select.addEventListener("pointermove", function () {
        mouseIsDown = true;
        log("pointermove");
    }, true);

    select.addEventListener("pointerup", function () {
        mouseIsDown = true;
        log("pointerup");
    }, true);

    select.addEventListener("mousedown", function () {
        mouseIsDown = true;
        log("mousedown");
    }, true);

    select.addEventListener("mouseup", function () {
        mouseIsDown = false;
        log("mouseup");
    }, true);

    select.addEventListener("click", function () {
        log("CLICK!!!");
    }, true);

    select.addEventListener("mousemove", function () {
        log("mousemove");
    }, true);

    $(select).on("touchstart touchmove touchend touchcancel", function (ev) {
        $.each(ev.originalEvent.touches, function (i, t) {
            logtouch(ev.type + "-touches", t);
        });
        $.each(ev.originalEvent.changedTouches, function (i, t) {
            logtouch(ev.type + "-changed", t);
        });
        $.each(ev.originalEvent.targetTouches, function (i, t) {
            logtouch(ev.type + "-target", t);
        });
    });
});