Copy to clipboard without flash (clipboard.js)

Updated . Posted . Visible to the public.

We used zeroclipboard.js in some of our projects but now we switched to clipboard.js Show archive.org snapshot because it does not rely on flash. Flash support of the major browsers has ended.

Some more advantages of clipboard.js:

  • it consists only of a single javascript file, so it does not trigger additional requests with rails
  • it automagically provides user feedback by selecting the text it has copied
  • it provides callbacks for success and error which make it easier to add custom behaviour after copying to the clipboard
  • it has different modes like copying from a text field or from a data attribute

How to (rails)

  1. Add clipboard.js to your project through bower or by downloading and adding the javascript file to the asset pipeline.

  2. Require it in your application.js:

    #= require clipboard
    
  3. Prepare your html: Your copy-to-clipboard-button either needs a data-clipboard-target attribute with a selector that points to an input field or a data-clipboard-text attribute with some text you want to copy.

    %textarea.form-control(id='copy-to-clipboard-field')
      Hello Clipboard!
    %button(type='button' copy-to-clipboard-button data-clipboard-target='#copy-to-clipboard-field')
    

    or

    %button(type='button' copy-to-clipboard-button data-clipboard-text="Hello Clipboard!")
    
  4. Prepare your javascript (coffeescript):

    clipboard = new Clipboard('[copy-to-clipboard-button]')
    clipboard.on 'success', ->
      # do cool things e.g. inform user that copy was successful
    clipboard.on 'error', ->
      # error handling
    
  5. That's it! Happy copying :)

Browser Support

  • Chrome 42+
  • Edge 12+
  • Firefox 41+
  • IE 9+
  • Opera 29+
  • Safari 10+

Error Handling

To improve the user experience on unsupported browsers, you can handle the error case with showing a tooltip. As clipboard.js will select the text to copy even for the unsupported browsers you can for example ask the users to press Ctrl+C. Best thing is, Ctrl+C even works with data-clipboard-text after the button was clicked.

Here's a coffeescript snippet using bootstrap tooltips:

clip.on 'error', (event) ->
  $button
  .tooltip(title: tooltipText())
  .tooltip('show')
  .on 'hidden.bs.tooltip', ->
    $button.tooltip('destroy')


tooltipText = ->
  text = ""
  if isOnMacOS()
    language = $('html').attr('lang')
    text = if language == 'de'
      '⌘-C zum Kopieren drücken'
    else
      'Press ⌘-C to copy'

  else
    language = $('html').attr('lang')
    text = if language == 'de'
      'Strg+C zum Kopieren drücken'
    else
      'Press Ctrl+C to copy'

  text


isOnMacOS = ->
  /Macintosh.*Mac OS/i.test(navigator.userAgent)
Last edit
Florian Leinsinger
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2016-11-15 11:24)