2

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

JasoonS
  • 1,432
  • 3
  • 13
  • 26

2 Answers2

3

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.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
1

In Elm 0.19, Browser.Dom has a focus task that will focus the DOM element with a given id. This will put the cursor in the element (if it is editable), but it will not select the text (i.e. highlight it). For that, you would need JavaScript select(). As far as I know, there's not a binding for that in Elm, but it must just be an oversight. It would be very easy to add -- almost the exact same as focus.

For now, if you want the text to be selected, ports are the only option.

QuinnFreedman
  • 2,242
  • 2
  • 25
  • 42