Hey friends!
It's another mini-tutorial Wednesday and today we’re learning something fun and useful: how to copy text to the clipboard using JavaScript.
You’ve probably seen buttons like “Copy Code” or “Copy Link” on websites. And you can build one too with just a few lines of JavaScript!
What We’ll Build:
- A text input
- A “Copy” button
- A small message that says “Copied!” when the text is copied
Step 1: Basic HTML
<div class="card">
<input type="text" id="copy-input" value="https://github.com/GiftinTech/" />
<button id="copy-btn">Copy Link</button>
<p id="message"></p>
</div>
Step 2: Basic Styling (Optional)
body {
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #f0f0f0;
margin: 0;
}
.card {
background: #fff;
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
text-align: center;
}
input {
width: 80%;
padding: 0.7rem;
font-size: 1rem;
margin-bottom: 1rem;
border: 1px solid #ccc;
border-radius: 6px;
}
button {
padding: 0.6rem 1.2rem;
font-size: 1rem;
background: #4caf50;
color: #fff;
border: none;
border-radius: 6px;
cursor: pointer;
}
button:hover {
background: #45a049;
}
#message {
margin-top: 1rem;
color: green;
font-weight: bold;
}
Step 3: JavaScript
const input = document.getElementById('copy-input');
const button = document.getElementById('copy-btn');
const message = document.getElementById('message');
button.addEventListener('click', () => {
const text = input.value;
navigator.clipboard.writeText(text).then(() => {
message.textContent = '✅ Link Copied!';
setTimeout(() => {
message.textContent = '';
}, 2000);
}).catch(() => {
message.textContent = '❌ Failed to copy!';
});
});
This uses the modern Clipboard API which works in most modern browsers.
Try It Yourself
I made a CodePen so you can try it out live:
👉 Open the Clipboard Copy Demo on CodePen
Feel free to change the text or style it your way.
💬 Over to You
Try making your own version that copies a password, link or email address.
Let me know if you try it, I'd like to see yours! Connect with me on GitHub
Was this tutorial helpful? Got questions? Or any insight to help me write better tutorials? Let me know in the 💬!
That’s it for today’s midweek mini tutorial!
I’m keeping things light, fun and useful; one small project at a time.
*If you enjoyed this, leave a 💬 or 🧡 to let me know. *
And if you’ve got an idea for something you'd like me to try out next Wednesday, drop it in the comments. 👇
Follow me to see more straight-forward and short tutorials like this :)
If you are curious about what I do, check out my Portfolio
:-)
Web trails
You can also find me here on LinkedIn
or here X (Twitter)
✍🏾 I’m documenting my learning loudly every Wednesday. Follow along if you're learning JavaScript too!
Let’s keep learning together!
Top comments (0)