marc walter

Focusing elements in Elm

2018-01-31 (Last updated on 2018-09-01)

A reminder how to focus input elements using Elm without I want to add elements to a list and automatically focus on them.

A nice solution on stackoverflow from robertjlooby is this:

The focus function in the elm-lang/dom package is used to set focus with a Task (without using any ports or JavaScript).

Internally it uses requestAnimationFrame to ensure any new DOM updates are rendered before it tries to find the DOM node to focus on.

type Msg
    = FocusOn String
    | FocusResult (Result Dom.Error ())

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        FocusOn id ->
            ( model, Dom.focus id |> Task.attempt FocusResult )

        FocusResult result ->
            -- handle success or failure here
            case result of
                Err (Dom.NotFound id) ->
                    -- unable to find dom 'id'
                Ok () ->
                    -- successfully focus the dom

He also created a fully working ellie example for Elm 0.18, which I converted to Elm 0.19.