Skip to content

Commit

Permalink
Focus search input when opening dropdown
Browse files Browse the repository at this point in the history
This uses a combination of `Dom.focus` and `Task.attempt` to create a
Cmd that will focus the DOM node with the given id. Since all Cmds
trigger a Msg when they are done but we just want to fire and forget, we
create a Noop Msg to deal with the situation.
  • Loading branch information
JoelQ committed Jul 5, 2017
1 parent c0e9979 commit 24d2f31
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
19 changes: 16 additions & 3 deletions Main.elm
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ module Main exposing (main)

import Html exposing (..)
import Html.Events exposing (onClick, onInput)
import Html.Attributes exposing (id)
import Dom
import Task


main =
Expand All @@ -28,7 +31,7 @@ type alias Model =

initialModel : Model
initialModel =
{ state = Open
{ state = Closed
, values = fruits
, selected = Nothing
, query = ""
Expand Down Expand Up @@ -59,7 +62,7 @@ viewOpen : Model -> Html Msg
viewOpen model =
div []
[ dropdownHead model.selected CloseSelect
, input [ onInput SearchInput ] []
, input [ id "search-box", onInput SearchInput ] []
, ul [] (List.map dropdownItem (filteredValues model))
]

Expand Down Expand Up @@ -101,13 +104,17 @@ type Msg
| CloseSelect
| ItemSelected String
| SearchInput String
| Noop


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Noop ->
( model, Cmd.none )

OpenSelect ->
( { model | state = Open }, Cmd.none )
( { model | state = Open }, focus )

CloseSelect ->
( { model | state = Closed }, Cmd.none )
Expand All @@ -119,3 +126,9 @@ update msg model =

SearchInput query ->
( { model | query = query }, Cmd.none )


focus : Cmd Msg
focus =
Dom.focus "search-box"
|> Task.attempt (always Noop)
1 change: 1 addition & 0 deletions elm-package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/dom": "1.1.1 <= v < 2.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
Expand Down

0 comments on commit 24d2f31

Please sign in to comment.