Creating ‘Copy to Clipboard’ feature on a web page with JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for creating ‘copy to clipboard’ feature on a web page with JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   input,
   button {
      padding: 8px;
   }
</style>
</head>
<body>
<h1>Creating Copy to Clipboard</h1>
<input class="textCopy" type="text" />
<button class="Btn">Copy Text</button><br /><br />
<input type="text" placeholder="paste here" />
<h3>Click on the above button to copy text from the textbox</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let textCopyEle = document.querySelector(".textCopy");
   BtnEle.addEventListener("click", () => {
      textCopyEle.select();
      document.execCommand("copy");
   });
</script>
</body>
</html>

Output

On typing something in the first textbox and clicking on the “Copy Text” button −

Pasting the text by left clicking and selecting paste in “paste here” textbox −


raja
Published on 17-Jul-2020 11:06:13
Advertisements