Get scrollHeight attribute from Textarea field

Hi guys,

I’m trying to build autoresizable textarea (by height)
and I’m stuck with getting a scrollHeight attribute from textarea field.

Regular js code look’s like this:

function getScrollHeight(id) {
     textareaObj = document.getElementById(id);
     var scrollH = textareaObj.scrollHeight;
     alert(scrollH);
}

How can I do the same in ELM?
Should I use custom JSON decoder for Html.Events.on event?

With Elm 0.19, look at getViewportOf from the new Browser package, it’s a task returning a Viewport on success where:

scene.height = scrollHeight
1 Like

Thanks, try it right after update from 0.18)

For now, I just want figure out how to do the same in 0.18.

I’m not sure that you can do it exactly as you want without ports in Elm 0.18, but the following package source could help:

An interesting package, I’ll check it.

For now I’ve finally got it with the next solution:

view = 
    textarea [getScrollHeight] []

-- Event Handlers

scrollHeightDecoder : Json.Decoder Int
scrollHeightDecoder =
    Json.at [ "target", "scrollHeight" ] Json.int


getScrollHeight : Attribute Msg
getScrollHeight =
    let
        succ height =
            Json.succeed (ScrollHeight height)
    in
        on "keyup" (Json.andThen succ scrollHeightDecoder)

And the equivalent JS code. So, basically elm’s “Html.Events#on” handles a similar “event” object from the code below:

  var textarea = document.getElementById("textarea")

  textarea.addEventListener("keyup", function (event) {
    console.log(event.target.scrollHeight)
  }

:+1:

This is almost what the package does for this part, except it uses on "input" and decode value at the same time:

inputDecoder : ConfigInternal msg -> Decoder msg
inputDecoder config =
    map2 (\t s -> config.onInput { textValue = t, state = s })
        (at [ "target", "value" ] string)
        (at [ "target", "scrollHeight" ] int
            |> map (State << getRows config)
)
1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.