Javascript copy text to clipboard. Hello Developers, How are you doing? In this tutorial, I will show you a tiny vanilla JavaScript project in which is to copy text to a clipboard using Vanilla Javascript. Well, You can see many websites specifically the eCommerce coupon section copy text to clipboard. I will give you the source code of JavaScript copy text to the clipboard and show you how to do it in any project.
Copy Text to Clipboard by Button Click

Well, Firstly we need an HTML file. So, create an HTML file which name is index.html. Then inside the index.html file paste this below code. Don’t forget to link with the JS file
HTML markup for copy to clipboard project
index.html
<!DOCTYPE html>
<html>
<head>
<title>Copy Text to Clipboard Javascript Tutorial</title>
</head>
<body>
<label>Dummy Coupon : </label>
<input type="text" value="TESTCOUPON" readonly class="coupon">
<button class="btn">Click Me</button>
<script src="script.js"></script>
</body>
</html>
Well, Our Html markup has been done. Now we have to create a JS file. Let’s create a JS file which name is script.js. Inside the js file paste this code.
Javascript code for copy to clipboard project
script.js
const $ = (data) => document.querySelector(data)
let btn = $('.btn')
let copyText = $('.coupon')
btn.addEventListener('click',(e)=>{
e.preventDefault()
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Coupon is : " + copyText.value);
})
Well, now time to check our code. Open the index.html file in your browser then click the “Click me” button and you can show an alert for copy text.
Thanks. Hope it will help you