JAVASCRIPT
Copy Text to Clipboard using Modern Clipboard API
Implement a robust and user-friendly copy-to-clipboard functionality using the modern JavaScript Clipboard API, providing instant feedback for web applications and improving user experience.
<button id="copyButton">Copy Text</button>
<p id="textToCopy">This is the text to be copied.</p>
<span id="copyFeedback" style="margin-left: 10px; color: green;"></span>
<script>
document.getElementById('copyButton').addEventListener('click', async () => {
const text = document.getElementById('textToCopy').textContent;
const feedbackSpan = document.getElementById('copyFeedback');
try {
await navigator.clipboard.writeText(text);
feedbackSpan.textContent = 'Copied!';
setTimeout(() => feedbackSpan.textContent = '', 2000);
} catch (err) {
feedbackSpan.textContent = 'Failed to copy!';
console.error('Failed to copy text: ', err);
setTimeout(() => feedbackSpan.textContent = '', 2000);
}
});
</script>
How it works: This snippet demonstrates how to copy text to the user's clipboard using the modern `navigator.clipboard.writeText()` method, which is part of the Asynchronous Clipboard API. It's an improvement over older methods as it's more secure, relies on user permission (often implicitly granted by a user action like a click), and returns a Promise, allowing for clear success/failure handling. The example also includes user feedback, briefly displaying 'Copied!' upon success, enhancing the user experience.