How to copy text to the clipboard with JavaScript?

CSSJavascriptWeb DevelopmentFront End Technology

Following is the code to copy text to the clipboard with JavaScript −


 Live Demo

<!DOCTYPE html>
button {
   border: none;
   outline: none;
   background-color: rgb(191, 187, 255);
   color: black;
   font-weight: bold;
   padding: 10px;
input {
   padding: 10px;
<h1>Clipboard example</h1>
<h2>Click the button below to copy text and paste it somewhere</h2>
<input type="text" value="Hello World" class="textInput" />
<button class="copy">Copy text</button>
document.querySelector(".copy").addEventListener("click", copyText);
function copyText() {
   var copyText = document.querySelector(".textInput");;
   copyText.setSelectionRange(0, 99999);
   alert("The copied text is: " + copyText.value);


This will produce the following output −

On clicking the ‘Copy text’ button −

Updated on 08-Apr-2020 11:03:32