Easy Tutorial
❮ Verilog2 Tutorial Mysql8 Error 1410 42000 You Are Not Allowed To Create A User With Grant ❯

Implementing Copy Function with JavaScript

Category Programming Techniques

This article will teach you how to implement a copy function using JavaScript.

Method One: Using Simple JavaScript Code

We can use the Clipboard API's Clipboard.writeText() or Clipboard.write() methods to overwrite the clipboard content with specified data.

Example

function myFunction() {
  /* Get the text content */
  var copyText = document.getElementById("myInput");

  /* Select the text to copy */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /* For mobile devices */

  /* Copy the content to the clipboard */
  navigator.clipboard.writeText(copyText.value);

  /* Alert the copied content */
  alert("Copied text: " + copyText.value);
}

You can provide a more user-friendly way to notify after copying:

Example

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);

  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Copied content: " + copyText.value;
}

function outFunc() {
  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Click the button to copy";
}

Method Two: Using the Third-Party Library clipboard.js (Recommended, Strong Compatibility)

-

Official website of clipboard.js: https://clipboardjs.com/

-

Github of clipboard.js: https://github.com/zenorocha/clipboard.js

We can download clipboard.js and include it in our project:

<script src="dist/clipboard.min.js"></script>

Of course, it's even simpler to use a domestic CDN library directly:

<script src="https://cdn.staticfile.org/clipboard.js/2.0.4/clipboard.min.js"></script>

Example

new ClipboardJS('#copyInput', {
  text: function(trigger) {
    return document.getElementById("myInput").value;
  }
}).on('success', function(e) {
  alert("Copy succeeded!!!");
  e.clearSelection();
}).on('error', function(e) {
  alert('Error!');
});

Browser Support for clipboard.js

** Click to Share Notes

Cancel

-

-

-

❮ Verilog2 Tutorial Mysql8 Error 1410 42000 You Are Not Allowed To Create A User With Grant ❯