elm / browser

Create Elm programs that run in browsers!
https://package.elm-lang.org/packages/elm/browser/latest/
BSD 3-Clause "New" or "Revised" License
312 stars 64 forks source link

Unable to preventDefault on `a` tag in Browser.application (alternative use case) #99

Open absynce opened 4 years ago

absynce commented 4 years ago

Browser.application ignores Html.Events.preventDefaultOn for a click handler within a link. Instead, it always returns a onUrlRequest message.

preventDefaultOn works as expected in Browser.element.

Example

SSCCE - GitHub project

Related to #74.

My SSCCE project has a larger example similar to my use case.

Use case

I am building a PWA with Elm. On a page, there's a list of items with the option to favorite each or drill in for more details. The favorite button is inside each item.

Links are ideal in case the user wants to open new tabs for items in the list without navigating away from the list, either with a right-click menu option or Ctrl + click on the link.

Workaround

My workaround is to change the outer link to a button with an onClick event and use Browser.Navigation.pushUrl from within the event message handler. This uses Html.Events.stopPropagationOn instead of Html.Events.preventDefaultOn from within the inner button.

onClickStopPropagation : msg -> Html.Attribute msg
onClickStopPropagation tagger =
    Html.Events.stopPropagationOn "click" <|
        Json.Decode.map alwaysStop
            (Json.Decode.succeed tagger)

alwaysStop : a -> ( a, Bool )
alwaysStop x =
    ( x, True )