7

Is there a way to copy a text from a div to clipboard when user clicks a button in elm 0.18?

I have looked at Clipboard.elm but I cannot make it compile and work in elm 0.18. So is there an official working way to do this in elm 0.18?

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • There a very few libraries that wrap js because they can't be published. So you will probably want to use a port. In this case that would be quite straight forward as you only need one way (to js) communication and that's the easier bit – Simon H Dec 10 '16 at 18:51

2 Answers2

9

If the target browser supports it, then you can do it via ports, for example:

elm:

type Msg = Copy

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case Debug.log "msg" msg of
    Copy -> (model, copy ())

port copy : () -> Cmd msg

-- VIEW
view : Model -> Html Msg
view model =
  div []
    [ Html.input [ id "copy" ] []
    , Html.button [ onClick Copy ] [ text "copy" ]
    ]

javascript:

const app = Elm.Main.fullscreen();
app.ports.copy.subscribe(() => {
  console.log('copy');
  document.querySelector('#copy').select();
  document.execCommand('copy');
});
Tosh
  • 35,955
  • 11
  • 65
  • 55
  • Note that this solution doesn't work in Firefox 41+ which is strict about the context in which you can execute the copy command. See https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Browser_compatibility for (a little) more info. Someone with a better understanding of the Elm runtime can probably explain why the callback isn't invoked in the event cycle... – Simon Calvin May 02 '17 at 16:12
1

As of Elm 0.19 a custom web component might be a good way to do this. I've had success with this one.

Nat Knight
  • 364
  • 2
  • 10