Adding Html element makes input-field lose focus

With the following code, when input text reaches 5 characters, the input field will lose focus.

If I change else branch to [ H.text "" ] then focus is not lost.

Is there a way to keep focus without requiring then and else branches to generate exact same number of Html elements?

Full example: https://ellie-app.com/8Gz95rL2Kx4a1

view : Model -> Html Msg
view model =
    let
        notice =
            if String.length model.text == 5 then
                [ H.text "Length is 5" ]

            else
                []
    in
    H.div []
        (notice
            ++ [ H.br [] []
               , H.input
                    [ A.type_ "text"
                    , A.value model.text
                    , E.onInput TextChanged
                    ]
                    []
               ]
        )

This happens because the dom elements under the top level H.div change order/quantity. Another option is to use Html.Keyed. I’ve made an example of how that works here https://ellie-app.com/8GBqDBhm5Lca1

1 Like

Funny I just recently was using similar thing as an Example here Afterthoughts around about Kernel code and custom operators complaints

Since @wolfadex already did pretty good job in explaining how to solve it I just add more technical note. This is not really problem with Elm, this is problem with VirtualDom diffing in general. React, Vue and other will suffer from similar issues without keyed node.

1 Like

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