Search code examples
clipboardelmclipboard.js

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?


Solution

  • 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');
    });