Is there any way to remove element focus?


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 =
        toMsg k =
            if k == 13 || k == 32 then
                Json.succeed ( msg, True )

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

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


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.