Search code examples
elm

How to auto select/highlight text in a text/input box in elm


Is there a way in elm to do the same thing as document.getElementById("test").select() does in javascript?

I have an input field that I want to act in a very similar way to highlighted share url when you click on share on here on StackOverflow:enter image description here

Even something like on github when you need to click the element to highlight it is fine: enter image description here

I know how to do this with ports (eg.). But I would prefer to do it directly in Elm. Is this possible? Will it be possible in future versions of Elm?

Thanks


Solution

  • There is currently a package with a few similar functions at elm-lang/dom, but they rely on native Javascript calls. See the focus example here.

    The Elm code:

    focus : Id -> Task Error ()
    focus =
      Native.Dom.focus
    

    and the native code...

    function focus(id)
    {
        return withNode(id, function(node) {
            node.focus();
            return _elm_lang$core$Native_Utils.Tuple0;
        });
    }
    

    If you wanted to build a local package that doesn't use ports, you would currently have to build a native package, which would work, but may not be backwards compatible in the future, and you won't be able to list the package publicly.

    I would recommend using ports.