Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Creating 'Copy to Clipboard' feature on a web page with JavaScript
The copy to clipboard feature allows users to easily copy text from input fields or other elements on a webpage. This functionality is essential for improving user experience in web applications.
Modern Approach Using Clipboard API
The modern way to implement copy to clipboard uses the Clipboard API, which is more secure and reliable than the deprecated execCommand method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy to Clipboard</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.container {
max-width: 500px;
margin: 0 auto;
}
input, button {
padding: 10px;
margin: 5px;
font-size: 16px;
}
.copy-btn {
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.copy-btn:hover {
background-color: #0056b3;
}
.status {
margin-top: 10px;
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Copy to Clipboard Demo</h1>
<input type="text" id="textInput" placeholder="Enter text to copy" value="Hello, World!">
<button class="copy-btn" onclick="copyToClipboard()">Copy Text</button>
<br><br>
<input type="text" placeholder="Paste here to test">
<div id="status" class="status"></div>
</div>
<script>
async function copyToClipboard() {
const textInput = document.getElementById('textInput');
const status = document.getElementById('status');
try {
await navigator.clipboard.writeText(textInput.value);
status.textContent = 'Text copied successfully!';
setTimeout(() => {
status.textContent = '';
}, 2000);
} catch (error) {
console.error('Failed to copy text: ', error);
status.textContent = 'Failed to copy text';
status.style.color = 'red';
}
}
</script>
</body>
</html>
Fallback Method for Older Browsers
For broader browser compatibility, you can implement a fallback using the older execCommand method when the Clipboard API is not available.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy with Fallback</title>
</head>
<body>
<input type="text" id="textInput" value="Sample text to copy">
<button onclick="copyWithFallback()">Copy Text</button>
<div id="message"></div>
<script>
function copyWithFallback() {
const textInput = document.getElementById('textInput');
const message = document.getElementById('message');
// Check if Clipboard API is supported
if (navigator.clipboard) {
navigator.clipboard.writeText(textInput.value).then(() => {
message.textContent = 'Copied using Clipboard API!';
}).catch(err => {
message.textContent = 'Failed to copy';
});
} else {
// Fallback for older browsers
textInput.select();
textInput.setSelectionRange(0, 99999); // For mobile devices
try {
document.execCommand('copy');
message.textContent = 'Copied using fallback method!';
} catch (err) {
message.textContent = 'Copy not supported';
}
}
}
</script>
</body>
</html>
Copying Static Text
You can also copy predefined text without requiring user input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy Static Text</title>
</head>
<body>
<p id="staticText">This is some static text that can be copied.</p>
<button onclick="copyStaticText()">Copy This Text</button>
<p id="feedback"></p>
<script>
async function copyStaticText() {
const textToCopy = "Visit TutorialsPoint.com for programming tutorials!";
const feedback = document.getElementById('feedback');
try {
await navigator.clipboard.writeText(textToCopy);
feedback.textContent = 'Static text copied to clipboard!';
feedback.style.color = 'green';
} catch (error) {
feedback.textContent = 'Copy failed';
feedback.style.color = 'red';
}
}
</script>
</body>
</html>
Key Differences
| Method | Browser Support | Security | Recommended |
|---|---|---|---|
| Clipboard API | Modern browsers | Secure (HTTPS required) | Yes |
| execCommand | Older browsers | Less secure | Fallback only |
Browser Compatibility Notes
The Clipboard API requires HTTPS in production and may not work in all browsers. Always test the feature and provide fallbacks for better user experience.
Conclusion
Use the modern Clipboard API with navigator.clipboard.writeText() for new projects, while keeping execCommand as a fallback for older browser support. Always handle errors gracefully and provide user feedback.
