Blog>
Snippets

Touch Event Delegation for Lists

Utilize event delegation to efficiently handle touch events on a list with many items, reducing the number of event listeners.
document.getElementById('myList').addEventListener('touchstart', function(event) {
  // Check if the target is a list item
  if (event.target.tagName === 'LI') {
    console.log('Touched list item:', event.target.textContent);
    // Handle touch event for the list item
  }
});
This code attaches a 'touchstart' event listener to an element with the ID 'myList'. Event delegation is used to handle touch events on list items. When a 'touchstart' event occurs, it checks if the event's target is a list item (LI tag). If it is, the event is handled accordingly. This reduces the number of event listeners required as we don't need one for each list item.
document.getElementById('myList').addEventListener('touchend', function(event) {
  // Check if the target is a list item
  if (event.target.tagName === 'LI') {
    console.log('Released touch on list item:', event.target.textContent);
    // Handle touchend event for the list item
  }
});
This code is similar to the previous snippet but it listens for 'touchend' events indicating the end of a touch. The same event delegation logic applies, where the event listener is only attached to the parent list and each list item is checked during event bubbling.