elm-css
elm-css copied to clipboard
onClick on link conflict with href
While using elm-css href
and onClick
, I get both a UrlRequested Internal
and a onClick
events.
I tried
onClick : Msg -> Attribute Msg
onClick msg =
preventDefaultOn "click" (Decode.map alwaysPreventDefault (Decode.succeed msg))
alwaysPreventDefault : msg -> ( msg, Bool )
alwaysPreventDefault msg =
( msg, True )
a [ href "#", onClick Logout ] [ text "Logout"]
With no luck so far. Any idea?
I still get that actually.
Apparently the solution would be to use button for actions and links for navigation.
I ended-up creating the following button class:
button.links {
background:none!important;
border:none;
padding:0!important;
font: inherit;
cursor: pointer;
color: #0275d8;
}
button.links:hover {
border-bottom: 1px solid #0275d8;
}
@Natim same happens to me since I'm using Elm 0.19, so I guess this behavior is more likely related to Elm 0.19 than to elm-css. I have ended up doing the same, using buttons rather than links :)
I recently made the switch to using links correctly again. Trying to leverage the browser features.
I still needed to do some "side-effects" on link clicks which requires onClick
.
I ended up with the following solution:
eventConfig : Bool -> Bool -> msg -> { message : msg, stopPropagation : Bool, preventDefault : Bool }
eventConfig stopPropagation preventDefault msg =
{ message = msg
, stopPropagation = stopPropagation
, preventDefault = preventDefault
}
onClickLink : msg -> Attribute msg
onClickLink msg =
custom "onclick" <| Json.map (eventConfig False True) (Json.succeed msg)
a [href "/demo", onClickLink GoToDemo] []
This solution prevents the link to work while still giving users the open in new tab
or copy link
functionality.
@littleStudent - can you confirm that you're using onclick
as the string rather than click
? Even with this kind of approach, this isn't working for me, though I recognise that it is probably an elm/html
issue. I can't see any discussion there.
I suspect this is at the core of it: https://github.com/elm/virtual-dom/blob/master/src/Elm/Kernel/VirtualDom.js#L458-L461
Not sure how one would do anything that would impact the core Elm event handler.
I've added a issue to elm/browser here which includes a work around of including a target
attribute on the a
link to avoid the UrlRequest message being sent to the app.