w3resource

JavaScript Clipboard API: Copy Text from Input Box

JavaScript Event Handling: Exercise-20 with Solution

Clipboard API for Copy

Write a JavaScript program that copies the content of a text box to the clipboard when a button is clicked.

Solution 1: Using navigator.clipboard.writeText

HTML and JavaScript Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>w3resource</title>
</head>
<body>
<script>
 // Create input box for text
const textBox = document.createElement('input'); 
textBox.type = 'text'; // Set the input type to text
textBox.placeholder = 'Type something to copy'; // Add a placeholder
document.body.appendChild(textBox); // Add the text box to the DOM

// Create button for copying text
const copyButton = document.createElement('button'); 
copyButton.textContent = 'Copy Text'; // Set button label
document.body.appendChild(copyButton); // Add the button to the DOM

// Add click event to the button to copy text
copyButton.addEventListener('click', () => {
  const text = textBox.value; // Get the value of the text box
  if (text) { // Ensure there's text to copy
    navigator.clipboard
      .writeText(text) // Copy text to the clipboard
      .then(() => {
        alert('Text copied to clipboard!'); // Show success message
      })
      .catch((err) => {
        console.error('Failed to copy text:', err); // Log any errors
      });
  } else {
    alert('Please enter some text to copy.'); // Alert if no text is entered
  }
});

  </script>
</body>
</html>


Output:

JavaScript   Copy Text

Explanation:

    1. Text Box and Button:

    • Creates an input box for the user to type text and a button to trigger the copy action.

    2. Clipboard API:

    • Uses navigator.clipboard.writeText to copy the content of the text box to the clipboard.

    3. Error Handling:

    • Handles potential errors when trying to access the clipboard.

    4. User Feedback:

    • Displays success or error messages based on the operation's result.

Solution 2: Using document.execCommand (Legacy Method)

HTML and JavaScript Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>w3resource</title>
</head>
<body>
<script>
 // Create input box for text
const textBox = document.createElement('input'); 
textBox.type = 'text'; // Set the input type to text
textBox.placeholder = 'Type something to copy'; // Add a placeholder
document.body.appendChild(textBox); // Add the text box to the DOM

// Create button for copying text
const copyButton = document.createElement('button'); 
copyButton.textContent = 'Copy Text'; // Set button label
document.body.appendChild(copyButton); // Add the button to the DOM

// Add click event to the button to copy text
copyButton.addEventListener('click', () => {
  textBox.select(); // Select the text inside the input box
  try {
    const successful = document.execCommand('copy'); // Attempt to copy the text
    const message = successful ? 'Text copied to clipboard!' : 'Failed to copy text.';
    alert(message); // Show appropriate message
  } catch (err) {
    console.error('Error copying text:', err); // Log any errors
  }
});

  </script>
</body>
</html>

Output:

JavaScript   Copy Text

Explanation:

    1. Text Box and Button:

    • Similar to Solution 1, creates an input box and button for user interaction.

    2. Legacy Clipboard API:

    • Uses the document.execCommand('copy') method to copy text, which works in older browsers.

    3. Text Selection:

    • The select() method ensures the text in the input box is selected before copying..

    4. User Feedback:

    • Displays success or failure messages depending on the operation's result.

Live Demo:

See the Pen javascript-event-handling-exercise-20 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Event Handling Exercises Previous: Geolocation API in JavaScript for user Location Access.
Event Handling Exercises Next: Desktop Notifications using JavaScript Web Notifications API.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.