How to modify an HTML element in Elm after the page is rendered?

时间:2016-10-20 19:52:12

标签: html elm

I'm writing a Single-Page Application in Elm. After the page is rendered, I need to modify some element's properties by some event.

For example, let's say I have a div with a set of classes assigned to it, and now I want to toggle its classList when a button on the page is pressed. How can I do that using just native Elm constructions?

I know that such goal can be achieved by using 'old good' JavaScript plus Elm ports, but is there a way for doing that by using just Elm with no 'external' JavaScript and Elm ports?

updated after some comments

  1. all the page is rendered and constructed by Elm, no 'external' JavaScript code;
  2. I would like to update just the HTML element, without re-rendering all the page.

1 个答案:

答案 0 :(得分:3)

You can construct your view function return div with appropriate classes depending on your model.

Following example, div gets class "black" when model is 1. No classes attached to the div otherwise. And click event updates the model.

-- UPDATE
type Msg
  = ToggleColor

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    ToggleColor -> (if model == 0 then 1 else 0, Cmd.none)

-- VIEW
view : Model -> Html Msg
view model =
  let
    classAttributes = classList [("black", model == 1)]
  in div [ classAttributes, onClick ToggleColor ] [ text "test" ]
相关问题