Blazor button onclick on desktop and ontouchstart on mobile

Viewed 625

I am using Blazor WebAssembly and I am trying to put a button on a web page which should work in desktop browsers using mouse, as well as mobile devices using touch. However, on mobile I want the button to respond to touch immediately, rather than wait for the user to let go.

Also I need to make sure it does not fire the same code twice on mobile, which is why I put the preventDefault=true in.

So I came up with the following:

<button
    @onclick="e => ToggleFlag(flag)"                                                
    @ontouchstart="e => ToggleFlag(flag)"
    @ontouchstart:preventDefault=true>
        @flag.DisplayValue
</button>

I thought the above code would work, but unfortunately Chrome is responding with the following "intervention" when I emulate the touch event:

blazor.webassembly.js:1 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080

After a bit more digging I found some useful info here and here.

What I take away from this, is that Blazor is registering its touch event listeners with {passive: true} by default which means Chrome will not allow the use of preventDefault, and as far as I am aware there is no way I can tell Blazor to use {passive: false}.

I have also tried removing @ontouchstart:preventDefault=true while applying the touch-action: none; style to the button, which didn't help as it just resulted in both listeners being called on touch.

What might be a possible solution here?

Thanks!

ps. as a work-around I have resorted to duplicating the button (each listening to a different event) and using CSS media queries to show/hide the relevant button depending on whether we're in desktop or mobile mode. Not ideal IMO and feels like a bit of a hack.

0 Answers
Related