How To do Javascript Copy Text to Clipboard by Button Click

javascript copy text to clipboard
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

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

javascript copy text to clipboard
javascript

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

Read More : 5 Vue Interview Questions You should Know

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published. Required fields are marked *