JavaScript Copy to Clipboard Feature with a Success Message
Improving user experience (UX) is a top priority for any modern website. If you are sharing code snippets, discount codes, or shareable links, forcing users to manually highlight and copy text is a frustrating experience.
In this tutorial, we will learn how to create a sleek JavaScript Copy to Clipboard button that displays a temporary "Copied!" success message. We will use the modern and secure Clipboard API to achieve this.
Why Use the Clipboard API?
In the past, developers relied on the document.execCommand('copy') method. However, this approach is now deprecated. The modern standard is the Navigator Clipboard API, which is asynchronous, more secure, and supported by all major browsers.
To understand more about how browser APIs work, check out our comprehensive guide on JavaScript DOM manipulation techniques.
Let’s dive into the code!
Step 1: The HTML Structure
First, we need a container holding the text we want to copy and the button that triggers the action. We will also include a hidden <span> to act as our success message.
<div class="copy-container">
<input type="text" id="textToCopy" value="npm install daily-aspirants-package" readonly>
<button id="copyBtn">Copy</button>
<span id="successMsg" class="hidden">Copied to clipboard!</span>
</div>
Note: Making the input readonly prevents mobile keyboards from popping up when users tap it.
Step 2: Styling with CSS
Let's add some basic CSS to make the button look clickable and to handle the visibility of our success message.
.copy-container {
display: flex;
align-items: center;
gap: 10px;
font-family: Arial, sans-serif;
}
input {
padding: 8px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 8px 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
.hidden {
opacity: 0;
visibility: hidden;
transition: opacity 0.3s ease;
}
.show-msg {
opacity: 1;
visibility: visible;
color: #28a745;
font-weight: bold;
}
Step 3: The JavaScript Magic
Now for the core functionality. We will add an event listener to the button. When clicked, it grabs the text from the input, writes it to the clipboard using navigator.clipboard.writeText(), and briefly displays the success message.
document.getElementById('copyBtn').addEventListener('click', async () => {
const textInput = document.getElementById('textToCopy').value;
const successMessage = document.getElementById('successMsg');
try {
// Modern approach using the Clipboard API
await navigator.clipboard.writeText(textInput);
// Show the success message
successMessage.classList.remove('hidden');
successMessage.classList.add('show-msg');
// Hide the message after 2 seconds
setTimeout(() => {
successMessage.classList.remove('show-msg');
successMessage.classList.add('hidden');
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
alert('Oops, unable to copy. Please try manually.');
}
});
How the Code Works:
async/await: The Clipboard API returns a Promise, so usingawaitensures the text is fully copied before the success message triggers.- Error Handling: The
try...catchblock ensures that if the browser blocks the clipboard action (e.g., due to missing permissions), the application doesn't break, and the user gets an alert. - SetTimeout: This resets the success message after 2000 milliseconds (2 seconds), keeping the UI clean.
For deeper technical documentation on clipboard permissions, I highly recommend reading the official MDN Web Docs on the Clipboard API.
Final Touch
Adding a "Copy to Clipboard" feature with a visual success message is a tiny detail that makes a massive difference in user retention and site functionality. By using the modern Clipboard API, your code is future-proof, secure, and incredibly lightweight.

Post a Comment