Skip to content

Instantly share code, notes, and snippets.

@vasiliishvakin
Created February 8, 2024 12:47
Show Gist options
  • Save vasiliishvakin/8cfce91dae8d37991d572236065d0a06 to your computer and use it in GitHub Desktop.
Save vasiliishvakin/8cfce91dae8d37991d572236065d0a06 to your computer and use it in GitHub Desktop.
touch-zoom-events-example.html
<!DOCTYPE html>
<html>
<header>
<title>Test</title>
<style>
.touchTest {
width: 800px;
height: 600px;
background-color: red;
}
</style>
<script>
let touchStarted = 0;
let prevDistance = null;
let touchStartedPoint = null;
const bindTouchEvents = () => {
const touchTest = document.querySelector(".touchTest");
touchTest.addEventListener("touchstart", (e) => {
// console.log("touchstart", e);
if (e.touches.length === 2) {
touchStarted = 2;
} else if (touchStarted < 2) {
touchStarted += 1;
}
if (touchStarted === 2 && touchStartedPoint === null) {
e.preventDefault();
e.stopPropagation();
touchStartedPoint = {
x: e.touches[0].clientX,
y: e.touches[0].clientY,
};
console.log("touchstart", e);
}
});
touchTest.addEventListener("touchmove", (e) => {
if (touchStarted === 2) {
if (e.touches.length === 2) {
e.preventDefault();
e.stopPropagation();
const diffX = e.touches[0].clientX - e.touches[1].clientX;
const diffY = e.touches[0].clientY - e.touches[1].clientY;
const distance = Math.sqrt(diffX * diffX + diffY * diffY);
if (prevDistance !== null) {
if (distance > prevDistance) {
console.log("zoom in");
} else if (distance < prevDistance) {
console.log("zoom out");
}
}
prevDistance = distance;
console.log("touchmove", e, distance);
}
}
});
touchTest.addEventListener("touchend", (e) => {
if (touchStarted === 2) {
e.preventDefault();
e.stopPropagation();
touchStarted = 0;
prevDistance = null;
touchStartedPoint = null;
console.log("touchend", e);
}
});
};
document.addEventListener("DOMContentLoaded", () => {
console.log("Document is ready!");
bindTouchEvents();
});
</script>
</header>
<body>
<h1>Test</h1>
<div class="touchTest"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment