How do I prevent the default ontouchend when the page is scrolling?

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?

Apache Cordova format used:

<a href="#" ontouchend="window.open('https://www.google.com', '_blank';">

If nothing else works, I can make the page a series of buttons at left with titles at right.

Hi @WebSteve, try using a click event instead as this shouldn’t get dispatched after scrolling anyway.

1 Like

I called it a “web app,” though it will actually be showing in iOS and Android devices. Sorry about that.

Will a click event still work?

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')
)
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.