Blog>
Snippets

Preventing Scrolling on Touchstart

Prevent the default scrolling behavior on touchstart to allow for custom touch interactions without page movement.
document.addEventListener('touchstart', function(event) {
  event.preventDefault();
}, { passive: false });
This code adds an event listener to the entire document that listens for the 'touchstart' event, which is the event triggered when a finger is placed on a touch screen. When the event occurs, the function calls 'event.preventDefault()' to prevent the default scrolling behavior associated with the touchstart event. The option '{ passive: false }' is included to ensure that the event listener can indeed call 'preventDefault', as some browsers may require this to be explicitly stated due to performance optimizations.