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:
- Creates an input box for the user to type text and a button to trigger the copy action.
- Uses navigator.clipboard.writeText to copy the content of the text box to the clipboard.
- Handles potential errors when trying to access the clipboard.
- Displays success or error messages based on the operation's result.
1. Text Box and Button:
2. Clipboard API:
3. Error Handling:
4. User Feedback:
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:
- Similar to Solution 1, creates an input box and button for user interaction.
- Uses the document.execCommand('copy') method to copy text, which works in older browsers.
- The select() method ensures the text in the input box is selected before copying..
- Displays success or failure messages depending on the operation's result.
1. Text Box and Button:
2. Legacy Clipboard API:
3. Text Selection:
4. User Feedback:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics