Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elm: copy text to clipboard

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?

like image 294
Buda Gavril Avatar asked Dec 09 '16 09:12

Buda Gavril


Video Answer


1 Answers

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');
});
like image 73
Tosh Avatar answered Sep 23 '22 17:09

Tosh