Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read content of contentEditable div?

Tags:

elm

I use a contentEditable div, and I want to access its content after the user has modified it (onBlur). How can I access the innerHtml or textContent of the DOM element ? Any idea ?

Here is a simple example :

import Html exposing (div, text)
import Html.App exposing (beginnerProgram)
import Html.Events exposing (onBlur)
import Html.Attributes exposing (contenteditable)


main =
  beginnerProgram { model = "Hello", view = view, update = update }


view model =
  div [contenteditable True, onBlur (SaveInput)] [ text model ]


type Msg = SaveInput


update msg model =
  case msg of
    SaveInput ->
      "ok"

I wish to replace "ok" with a formula using textContent to get the value entered by the user. I am using elm v 0.17.

like image 964
Pierre Carbonnelle Avatar asked May 14 '16 19:05

Pierre Carbonnelle


1 Answers

Here is one way to do it. You'll have to extract the value from the event object using Json.Decode.

import Html exposing (Html, div, text)
import Html.App exposing (beginnerProgram)
import Html.Events exposing (onBlur, on)
import Html.Attributes exposing (contenteditable, id)
import Json.Decode as Json
import Debug

main : Program Never
main = beginnerProgram { model = "Hello" , view = view , update = update }

type alias Model = String

view : Model -> Html Msg
view model =
  div [ contenteditable True ,on "blur" (Json.map SaveInput     targetTextContent)]
    [ text model ]

targetTextContent : Json.Decoder String
targetTextContent =
  Json.at ["target", "textContent"] Json.string

type Msg = SaveInput String

update : Msg -> Model -> Model
update msg model =
  case msg of
    SaveInput str -> (Debug.log "saving" str)
like image 156
Tosh Avatar answered Oct 12 '22 05:10

Tosh