HTML
HTML is a markup hypertext language that gives structure to our website. We will use HTML to create an input field that will be used by the user to enter some text. Then a button will be created, which when clicked will copy anything that is in the input field. In the end, we will use a script tag to reference the JavaScript file which has JavaScript code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comment Box</title>
</head>
<body>
<input type="text" id="mytext">
<button onclick="handleClick()">Copy</button>
<script src="code.js"></script>
</body>
</html>
We used the id attribute in the input tag so we can reference it later from the JavaScript File. We also initialized the onclick event which means whenever the user clicks on the copy button, the handleClick() function will run.
JavaScript
We initialized a function with the name of handleClick() so that whenever the user clicks on the copy button the code in this function will start executing. Inside the function, using the id attribute of the input field, we referenced the input field and attached .value in the end so that the input field value is stored in the variable input. Now that we have the value of the input field, let us copy the value to the clipboard using the navigator.clipboard.write() function where we pass the input variable as a parameter. The input variable text is now copied to the clipboard. In the end, we alert the input variable.
/* Save value of myText to input variable */
var input = document.getElementById("myText").value;
/* Copy the text inside the text field */
navigator.clipboard.writeText(input);
alert("Copied Text: " + input);
}
We entered the text copy to clipboard article in the input field and now we will click on the copy button. We will see an alert showing the copied text:
Go to a new window or a word file and press CTRL+V which will paste the copy to the clipboard article in that window.
Conclusion
Copy to clipboard button comes in very handy when you are making a website that uses information from one section to another hence improving user experience. Copy to clipboard button is also a project for a beginner who wants to practice his JavaScript skills.
In this post, we implemented the copy to the clipboard button in JavaScript along with screenshots and a GIF.