Is there any way to remove element focus?

Hi.

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.

Thanks!

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" ]
        ]

https://ellie-app.com/6jH2fLcZQyca1

This will ensure that the buttons can be activated with the keyboard but they will not generate the extra “onClick” message.

2 Likes

Thanks, that worked wonderfully. I didn’t now you could create “custom” events or that “preventDefaultOn” existed.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.