Quick Touch Events 2 (easing)
// no scrolling on mobile
document.addEventListener('touchmove', e => e.preventDefault(), {
passive: false
});
const hasTouch =
navigator.maxTouchPoints != null && navigator.maxTouchPoints > 0;
// looking forward to `navigator?.maxTouchPoints > 0`
// being better supported
function touchify(e) {
const touch = [];
touch.x = touch.y = 0;
if (e.touches != null && e.touches.length > 0) {
touch.x = e.touches[0].clientX;
touch.y = e.touches[0].clientY;
for (let i = 0; i < e.touches.length; i++) {
touch[i] = e.touches[i];
}
} else {
touch.x = e.clientX;
touch.y = e.clientY;
touch[0] = { clientX: e.clientX, clientY: e.clientY };
}
return touch;
}
let moveOrTouchMove;
if (hasTouch) {
moveOrTouchMove = 'touchmove';
} else {
moveOrTouchMove = 'mousemove';
}
function dot(x, y, radius, color) {
const el = document.createElement('div');
const size = `${radius * 2}px`;
Object.assign(el.style, {
position: 'absolute',
left: `${x}px`,
top: `${y}px`,
width: size,
height: size,
transform: `translate(${-radius}px, ${-radius}px)`,
borderRadius: '50%',
background: color
});
el.classList.add('dot');
document.body.appendChild(el);
return el;
}
let dotX = 100,
dotY = 100,
touchX = 200,
touchY = 150,
damp = 12,
dotEl = dot(dotX, dotY, 20, 'red');
document.addEventListener(moveOrTouchMove, e => {
const { x, y } = touchify(e);
touchX = x;
touchY = y;
});
function loop() {
dotX += (touchX - dotX) / damp;
dotY += (touchY - dotY) / damp;
Object.assign(dotEl.style, {
left: `${dotX}px`,
top: `${dotY}px`
});
window.requestAnimationFrame(loop);
}
loop();
Move your mouse on desktop or your finger on mobile – watch the red dot follow…
This is a simpler version of some of the things used in yesterdays post – just a quick way to normalize touch events – just one of many ways to do this – for simple stuff this is my goto
.
If you want to try it out on its own page – take a look here (specifically good for trying it on mobile).
You’ll probably want a to use a meta tag like this – for the full effect.
<meta name="viewport" content="width=device-width, initial-scale=1.0">