Touch Event

by humanzing

HTML

<div id="touchTest">
    <span id="toleft" class="toleft demoArrow">&#10094;</span>
    <span id="toright" class="toright demoArrow">&#10095;</span>
</div>

CSS

html, body {
    width:100%;
    height:100%;
}
#touchTest {
    background-color:red;
    width:300px;
    height:300px;
    position:relative;
}
.demoArrow {
    font-size:75px;
    position:absolute;
    top:0;
    display:none;
}
.toleft {
    left:0;
}
.toright {
    right:0;
}

JavaScript

document.getElementById("touchTest").addEventListener('touchstart', handleTouchStart, false);
document.getElementById("touchTest").addEventListener('touchmove', handleTouchMove, false);
document.getElementById("touchTest").addEventListener('mousedown', handleTouchStart, false);
document.getElementById("touchTest").addEventListener('mouseup', handleTouchMove, false);
/*fleches*/
var tla = document.getElementById("toleft");
var tra = document.getElementById("toright");

var xDown = null;
function handleTouchStart(evt) {
    xDown = evt.touches ? evt.touches[0].clientX : evt.clientX;
};
function handleTouchMove(evt) {
    if (!xDown) {
        return;
    }
    xUp = evt.touches ? evt.touches[0].clientX : evt.clientX;
    if (xUp-xDown > 5) {
    	console.log("toright")
        tla.style.display = "none";
        tra.style.display = "inline";
        console.log("toright");
    } else if (xUp-xDown < -5) {
    	console.log("toleft")
        tra.style.display = "none";
        tla.style.display = "inline";
        console.log("toleft");
    }
    xDown = null;
};