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:
Add clipboard.js
to your project through bower or by downloading and adding the javascript file to the asset pipeline.
Require it in your application.js
:
#= require clipboard
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!")
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
That's it! Happy copying :)
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)