In a recent web application, I wanted to create a dynamic effect where button images change between pressed and unpressed states using touch input. This effect is especially appealing on mobile devices. When you tap and hold the button, the image switches to the pressed state. If you slide your finger off, it reverts to the unpressed state, and it toggles back and forth seamlessly. Additionally, you can trigger an action event when the tap (click) occurs.
Here is some sample code that demonstrates this effect using JavaScript touch events. Feel free to incorporate it into your projects.
<html>
<body>
<style>
.container {
position: absolute;
top: 100;
left: 100;
}
button {
border: none;
background-color: transparent;
touch-action: none;
}
</style>
<div class="container">
<button id="clickMe">
<img id="buttonImage" width="400" height="200" src="button_off.png">
</button>
</div>
<script>
let rect;
let buttonIsPressed;
const clickMe = document.getElementById("clickMe");
const buttonImage = document.getElementById("buttonImage");
const eventType = "ontouchend" in document ? "touchend" : "click";
if (buttonImage) {
rect = buttonImage.getBoundingClientRect();
}
function onTouchStart() {
console.log("onTouchStart");
buttonIsPressed = true;
if (buttonImage) buttonImage.src = "button_on.png";
}
function onTouchMove(e) {
if (buttonImage) {
if (e.touches[0].clientX >= rect.x && e.touches[0].clientX <= (rect.x + rect.width) &&
e.touches[0].clientY >= rect.y && e.touches[0].clientY <= (rect.y + rect.height)) {
buttonImage.src = "button_on.png";
buttonIsPressed = true;
} else {
buttonImage.src = "button_off.png";
buttonIsPressed = false;
}
}
}
function onTouchEnd() {
console.log("onTouchEnd");
buttonIsPressed = false;
if (buttonImage) buttonImage.src = "button_off.png";
}
if (clickMe) {
clickMe.addEventListener(eventType, () => {
if (!buttonIsPressed) return;
console.log("Event Triggered : Button Pressed");
});
clickMe.addEventListener("touchstart", onTouchStart, { passive: true});
clickMe.addEventListener("touchmove", onTouchMove, { passive: true});
clickMe.addEventListener("touchend", onTouchEnd, { passive: true});
}
</script>
</body>
</html>
Leave a Reply