Blog>
Snippets

Basic Touch Event Listeners

Add touchstart, touchmove, and touchend event listeners to an element to detect and handle basic touch interactions.
var touchArea = document.getElementById('touchArea');

// Touch Start Event Listener
touchArea.addEventListener('touchstart', function(event) {
    // Prevent default behavior
    event.preventDefault();
    console.log('Touch started:', event.touches);
}, false);

// Touch Move Event Listener
touchArea.addEventListener('touchmove', function(event) {
    // Prevent default scrolling
    event.preventDefault();
    console.log('Touch moved:', event.touches);
}, false);

// Touch End Event Listener
touchArea.addEventListener('touchend', function(event) {
    // You may decide to prevent default behavior
    // event.preventDefault();
    console.log('Touch ended:', event.changedTouches);
}, false);
This code selects an HTML element with the ID 'touchArea' and adds three event listeners to it: 'touchstart', 'touchmove', and 'touchend'. When a touch event starts, moves, or ends, it logs the touch event object to the console and prevents the default browser action to enhance the touch interaction handling.