An Introduction to Elm Series: Solution to ‘Buttons’ example 1

In, you are given a working code that produces a simple counter which can be incremented or decremented via two buttons on an HTML page.

Your task is to add a new feature to this code, which is to create a new button that will reset the counter. Following you will find a proposed solution to the task. What we did was to create a new message which when received it would zero the model value and then we attached it to a new button we created.

The full solution is as follows and we highlighted all the lines that were added for this additional functionality to work:

import Html exposing (Html, button, div, text)
import Html.App as Html
import Html.Events exposing (onClick)

main =
    { model = model
    , view = view
    , update = update


type alias Model = Int

model : Model
model =


type Msg
  = Increment
  | Decrement
  | Reset

update : Msg -> Model -> Model
update msg model =
  case msg of
    Increment ->
      model + 1

    Decrement ->
      model - 1

    Reset ->


view : Model -> Html Msg
view model =
  div []
    [ button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick Increment ] [ text "+" ]
    , button [ onClick Reset ] [ text "Reset" ]

You can download the solution from here 1-button.elm (compressed) (147 downloads)

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One thought on “An Introduction to Elm Series: Solution to ‘Buttons’ example