Copy to clipboard implemented by javascript

"Copy to clipboard" is a function we use dozens of times a day, but the client API is always lacking. Some older APIs and browser implementations need a terrible "are you sure?" -Before a style conversation, content will be copied to the clipboard - not suitable for availability or trust. About seven years ago, I blogged ZeroClipboard , a more innovative way to copy content to the clipboard solution.
Hey, we all hate Flash, but functionality has always been the main goal, and it's very effective for that purpose, so we have to admit that it's a decent solution. A few years later, we have a better, Flash free solution: clipboard.js. View Demo . The clipboard.js API copied to the clipboard is short and easy to use. Its usage is as follows:
1. Copy and cut Textarea and Input values:

/* Textarea - Cut
<textarea id="bar">hello</textarea>
<button class="copy-button" data-clipboard-action="cut" data-clipboard-target="#bar">Cut</button>
*/
var clipboard = new Clipboard('.copy-button');

/* Input - Copy
<input id="foo" type="text" value="hello">
<button class="copy-button" data-clipboard-action="copy" data-clipboard-target="#foo">Copy</button>
*/
var clipboard = new Clipboard('.copy-button');
  1. Copy element innerHTML
/* HTMLElement - Copy
<div id="copy-target">hello</div>
<button class="copy-button" data-clipboard-action="copy" data-clipboard-target="#copy-target">Copy</button>
*/
var clipboard = new Clipboard('.copy-button');

3.Target and Text functions

// Contents of an element
var clipboard = new Clipboard('.copy-button', {
    target: function() {
        return document.querySelector('#copy-target');
    }
});

// A specific string
var clipboard = new Clipboard('.copy-button', {
    text: function() {
        return 'clipboard.js is awesome!';
    }
});
  1. Event callback function after operation:
var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
    console.log(e);
});

clipboard.on('error', function(e) {
    console.log(e);
});

demo address: Preview demo

Without flash component, the api is simple and compatible with all mainstream browsers, which makes clipboard.js popular with many users and web,

Original address: JavaScript Copy to Clipboard

Tags: Javascript

Posted on Mon, 04 May 2020 06:48:42 -0700 by bobicles2