Reputation: 384
The following HTML page is from a demo for clipboard.js from clipboardjs.com. I like how this works, where it highlights the text.
However, I have a requirement to have it change the button from displaying "Copy" to "Copied!" once the user has clicked on the button and it has successfully completed the copy to clipboard.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>target-input</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- 1. Define some markup -->
<input id="foo" type="text" value="hello">
<button class="btn" data-clipboard-action="copy" data-clipboard-target="#foo">Copy</button>
<!-- 2. Include library -->
<script src="../dist/clipboard.min.js"></script>
<!-- 3. Instantiate clipboard -->
<script>
var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
console.log(e);
});
clipboard.on('error', function(e) {
console.log(e);
});
</script>
</body>
</html>
Upvotes: 0
Views: 2272
Reputation: 794
This worked for me:
clipboard.on('success', function(e) {
e.clearSelection();
e.trigger.textContent = 'Copied!';
});
Quoting from this tutorial on the part of Working with the Custom Events:
clearSelection()
utility function from Clipboard. Adding this is optional.Upvotes: 3
Reputation: 9988
clipboard.on('success', function(e) {
document.querySelector('data-clipboard-target="#foo"').value = 'Copied!';
});
Upvotes: 0