How to apply event.preventDefault() on <LiveRedirect> component?
travelmassive opened this issue · comments
Is there a way to apply an onclick="event.preventDefault();" on a LiveRedirect component?
My use case:
I am displaying a profile picture of a member that has a tippy/hover with more information about that member. Clicking the profile image goes to the member's profile page, using LiveRedirect. Mobile users need to click the profile image to see the tippy (since they can't hover), so I need to prevent the LiveRedirect from firing.
Ideally I would detect mobile in JS and present the LiveRedirect from firing. However, I can't seem to do this. This method does work for Link but that's not a great solution given what we have with Surface and LiveView!
Here's what it looks like:
<LiveRedirect opts={onclick: "if (isTouchDevice()) { event.preventDefault(); }"} to={Route...}>
[Profile picture with a tippy]
</LiveRedirect>
Your Environment
Surface: v0.9.1
LiveView: v0.18.3
Elixir: v1.13.4
Thanks for any assistance! ~ Ian
Thanks for asking a question with a clear example.
This should help you:
<LiveRedirect to={Route...} opts={onclick: "if (isTouchDevice()) { event.preventDefault(); event.stopImmediatePropagation(); }"}>
[Profile picture with a tippy]
</LiveRedirect>
I tested it quickly, and it seems to work. I found the solution here: phoenixframework/phoenix_live_view#492
Most of the time, the best way to tackle this kind of issue is to first find a solution with a plain old phoenix live view template, and then translate it to Surface, as Surface is on top of LV. Your example won't work either with LV, so I first tried to solve it with LV.
I am closing the issue. If it does not solve your issue, feel free to reopen it.
Hi Malian,
Thanks for the solution and explanation. Looks like I was missing the event.stopImmediatePropagation().
I've got it working and you can see it in action at https://www.travelmassive.com/
Best,
Ian