Search code examples
touch-eventalpine.js

How do I prevent @click event when triggering @touchstart via alpine.js


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.


Solution

  • 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>