0

I am using alpine.js with the following code:

<a href="#home" @click="myFunction(event)"
   @touchstart.prevent="myFunction(event)"> 
  My Link
</a>
...
function myFunction(ev) {
  console.log(ev.type + ' -> myfunc');
}

I am expecting the console to only output:

touchstart-> myfunc

However, it is still triggering the click event and the output is:

touchstart-> myfunc
click -> myfunc

I have also tried @touchstart.stop but to no avail. Any ideas as to what's going on or if I'm doing something wrong?

Update: Originally I was testing via Firefox's dev tools. However, when I tried on Chromium's dev tools, the touch/click events behaved as expected. This means it could be a bug in the way Firefox dev tools handles touch/click events.

umphy
  • 126
  • 1
  • 10

1 Answers1

0

What comes to mind is that stopping propagation of a touch event won't stop the click event from triggering.

To deal with this userland using Alpine.js, you probably need to set an "isTouch" or equivalent flag, and while the touch is happening, ignore clicks.

Eg.

<div x-data="{ isTouch: false }">
  <a href="#home" @click="!isTouch && myFunction($event)"
   @touchstart.prevent="isTouch = true; myFunction($event)"> 
    My Link
  </a>
</div>
Hugo
  • 3,500
  • 1
  • 14
  • 28
  • I wish something like that can be automatic within the library. If touch events are detected, then it should disable click events – umphy May 06 '20 at 02:00
  • I'm not sure that's correct, "click" is a valid event on mobile. Apart from that, I think this is beyond the scope of a StackOverflow question, let me know if my solution doesn't work or maybe approve it if it does? – Hugo May 07 '20 at 08:29
  • Yes you're absolutely right. Come to think of it, there are notebooks with touch screens which support both click and touch events. – umphy May 08 '20 at 12:55
  • Yes but how to prevent default only on certain condition? e.g. autocomplete input, press tab to move down the list, but only if the list of results is visible. I found it, done like this... ```@keydown.tab="if(suggestions.length > 1) { moveDownList(); $event.preventDefault(); }"``` – ChrisDeDavidMindflowAU Dec 22 '22 at 14:56