#front end technology
#webdevelopment
#javascript

Copy Text to the Clipboard with JavaScript

Anonymous

AnonymousOct 20, 2023

Copy Text to the Clipboard with JavaScript

You can copy text to the clipboard in JavaScript by using the Clipboard API or document.execCommand() method. Here, I'll provide examples of both methods.

Method 1: Using the Clipboard API (Recommended)

Note: The Clipboard API is a more modern and reliable way to copy text to the clipboard. It's widely supported in modern browsers.

HTML:

<!DOCTYPE html>
<html>

<head>
  <title>Copy to Clipboard Example</title>
</head>

<body>
  <div id="textToCopy">Text to copy</div>
  <button id="copyButton" onclick="copyToClipboard()">Copy Text</button>

  <script src="script.js"></script>
</body>

</html>

JavaScript (script.js):

// Function to copy text to clipboard using the Clipboard API
const copyToClipboard = async () => {
  const textToCopyDiv = document.getElementById('textToCopy');
  const textToCopy = textToCopyDiv.innerText;
  try {
    await navigator.clipboard.writeText(textToCopy);
    console.log('Text copied to clipboard: ' + textToCopy);
  } catch (err) {
    console.error('Unable to copy text: ', err);
  }
};

Method 2: Using document.execCommand() (Not recommended for modern browsers)

This method involves creating a temporary input element to manipulate the clipboard.

Note: It's less recommended because it's less reliable and can be blocked by some browser security settings, but it can be useful for compatibility with older browsers.

HTML:

<!DOCTYPE html>
<html>

<head>
  <title>Copy to Clipboard Example</title>
</head>

<body>
  <textarea id="textToCopy">Text to copy</textarea>
  <button id="copyButton">Copy Text</button>

  <script src="script.js"></script>
</body>

</html>

JavaScript (script.js):


  const copyButton = document.getElementById('copyButton');
  function copyToClipboard() {
  const textToCopyTextarea = document.getElementById('textToCopy');
  textToCopyTextarea.select();
  document.execCommand('copy');
  console.log('Text copied to clipboard: ' + textToCopyTextarea.value);
  }
  copyButton.addEventListener('click', copyToClipboard);

The Clipboard API method is preferred for modern web applications as it's more secure and reliable. However, the document.execCommand() method can still be useful in situations where the Clipboard API is not available, although it should be used with caution due to potential security and compatibility issues.

Happy Coding! ❤️