How to read contents of contentEditable div?

I am using div contentEditable and I want to access its content after the user has changed it (onBlur). How can I access innerHtml or textContent of a 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 want to replace “ok” with a formula using textContent to get the value entered by the user. I am using elm v 0.17.

+5
source share
2 answers

Here is one way to do it. You will need 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) 
+8
source

I combined Tosh with a little extra user help using Dom.focus so that after clicking on an element to edit, the cursor becomes correctly visible.

 update ... = EditTitle -> ( model | editTitle = True } , Dom.focus "view-title" |> Task.attempt FocusResult ) viewNameEditor : Model -> Html Msg viewNameEditor m = let attrs = if m.editTitle then [ contenteditable True , on "blur" (Json.map SaveViewName targetTextContent) , id "view-title" ] else [ contenteditable False , onClick EditTitle , id "view-title" ] in div attrs [ text current.name ] 
0
source

All Articles