You might have seen a “click to copy” or “copy to clipboard” buttons in multiple web applications. This button allows the users to quickly copy text such as code snippets, URLs, passwords, or generated output with a single click. You would have probably seen this feature on documentation sites, developer tools, and online utilities.
A copy button enhances the user experience and improves the usability of the web application. This button can be used for multiple use cases such as:
If you have ever wanted to build something like that, then you have landed at the right place. In this tutorial, we will learn how to create a copy button in a webpage. We shall build this purely using HTML and JavaScript. Let’s head on to the tutorial…
All modern web browsers provide the Clipboard API. This API has a lot of methods which helps you work with clipboard. In this tutorial, we shall use the method which allows JavaScript to copy text programmatically. Here is the syntax for using this method:
navigator.clipboard.writeText(text)
Let’s demonstrate the usage of this method inside an HTML page…
Create an HTML page, add a text area field and a button that users can click to copy the text. Add the Javascript code. The complete HTML code snippet is given below for reference.
<!DOCTYPE html>
<html>
<head>
<title>Copy Button Example</title>
</head>
<body>
<h2>Copy Text Example</h2>
<textarea id="copyText" rows="10" cols="40">
This is the text you want to copy.
</textarea>
<br>
<button id="copyBtn" onClick="clickToCopy()">Copy</button>
</div>
<script>
function clickToCopy(){
const copyBtn = document.getElementById("copyBtn");
const copyText = document.getElementById("copyText");
navigator.clipboard.writeText(copyText.value);
}
</script>
</body>
</html>
You can copy this code and preview it live using our Online HTML Code Editor
You can also further enhance this copy button by adding some more functionalities such as:
Ok that’s it for this tutorial. You can build this feature with just a few lines of JavaScript which can significantly improve your website’s user experience.
I hope you found this tutorial useful. Do share your experience on our social media channels.
Check out some of our other tutorials – HTML Tutorial | JavaScript Tutorial
Fully customizable CRM Software for Freelancers and Small Businesses