I have a series of buttons in a web app. If you want to scroll down the page, you’ll touch a button as you do so, and lifting your finger will open the page of that button.
How do I prevent the default button behavior when scrolling?
Yes I assumed that from the touch event. :-) But yes, it should work… there used to be some browser compatibility issues in the past, but AFAIK this is not the case any more (not for anchor elements at any rate).
Anyway if you want to stick to touch events something like this should do the trick:
const addTouchListener = (element, callback) => {
element.addEventListener('touchstart', () => {
// Add a one-time touchend event listener
// each time a touchstart event occurs...
element.addEventListener('touchend', callback, { once: true })
})
element.addEventListener('touchmove', () => {
// ... but remove that touchend listener
// whenever the user swipes the screen
element.removeEventListener('touchend', callback)
})
}
// Apply to #my-button
addTouchListener(
document.getElementById('my-button'),
() => window.open('https://www.google.com', '_blank')
)