Implementing click to copy in JavaScript

January 28, 2024

The original problem was how to implement a copy button across browsers using clipboardData. Internet Explorer supported window.clipboardData.setData('text', 'content'). In IE, clipboardData was a property of window.

Other browsers expose clipboard data on the corresponding event object. That design helps prevent unauthorized access. For cross-browser support, my original conclusion was that we could not implement click to copy with clipboardData.

💡 Update: Modern browsers also provide a Clipboard API for writing data directly to the clipboard.

Here is the approach I used:

Create a hidden input field.

When the user clicks the button, put the text to copy into that field.

Select the contents with input.select(). This selection method works on an input or a textarea.

// document.execCommand("copy") executes the browser's copy command.
function copyText() {
   var text = document.getElementById("text").innerText; // The text can also be passed as an argument.
   var input = document.getElementById("input"); // Find the hidden input.
   input.value = text; // Set the field's value.
   input.select(); // Select the text.
   document.execCommand("copy"); // Run the browser's copy command.
   alert("Copied");
 }

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-01-28). Implementing click to copy in JavaScript. https://caiborui.com/blog/2024-01-28-zh-js%E7%82%B9%E5%87%BB%E5%A4%8D%E5%88%B6%E5%8A%9F%E8%83%BD-entrans

@misc{borui2024-761c25dc,
  author = {borui},
  title = {{Implementing click to copy in JavaScript}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-01-28-zh-js%E7%82%B9%E5%87%BB%E5%A4%8D%E5%88%B6%E5%8A%9F%E8%83%BD-entrans}
}