Blog>
Snippets

Incorporating Touch Feedback

Give visual or haptic feedback to users when touch events are detected to improve user experience on touch-enabled devices.
// Function to provide visual feedback on touch
function touchVisualFeedback(event) {
    var touchedElement = event.target;
    touchedElement.classList.add('touched');
    // Set a timeout to remove the class
    setTimeout(function() {
        touchedElement.classList.remove('touched');
    }, 200); // 200ms for visual effect duration
}

// Attach the touchVisualFeedback function to touchstart event
document.addEventListener('touchstart', touchVisualFeedback);
This code adds visual feedback by attaching a class to the target element of a touch event (e.g., to change the background color), and then removes the class after a short delay to create a tapping effect.
// Use the Vibration API for haptic feedback
function touchHapticFeedback() {
    if ('vibrate' in navigator) {
        navigator.vibrate(50); // Vibrate for 50 milliseconds
    }
}

// Attach the touchHapticFeedback function to touchstart event
// Check for touch device to avoid errors on non-touch-enabled devices
if ('ontouchstart' in window) {
    window.addEventListener('touchstart', touchHapticFeedback);
}
This snippet demonstrates how to provide haptic feedback on a touch-enabled device using the Vibration API. It checks if the API is supported and then vibrates the device for a short duration on a touch event.