I’m using the Enter key for input in my app and, as you know, when an element is focused and you press Enter said element gets “clicked”. That leads to strange behavior in my app because it emits both the Enter key’s message and the message from the button that was “clicked”, in that order.
Is there any solution beside using another key? I’m writing a calculator and using the numpad’s Enter is really convenient.
You could create an event handler that would trap the activation event like this:
onActivation : msg -> Attribute msg
onActivation msg =
let
toMsg k =
if k == 13 || k == 32 then
Json.succeed ( msg, True )
else
Json.fail "no activation"
in
preventDefaultOn "keydown" (Json.andThen toMsg keyCode)
and then use it like this:
view : Model -> Html Msg
view model =
div []
[ button [ onClick Increment, onActivation Increment ] [ text "+1" ]
, div [] [ text <| String.fromInt model.count ]
, button [ onClick Decrement, onActivation Decrement ] [ text "-1" ]
]