Copy to clipboard in JavaScript

Objectives of the blog

After the reading of this blog, you will be able to know how data can be copy to clipboard with help of java script.

Benefit of copy to clipboard functionality

In the current web world, it’s all about the user experienced from your site. During our work on any site we copy content from one place and paste at another place. It will be really helpful to the user if a site give a functionality of click to copy. It saves the time and effort of the user to select and copy the content.

Implementation of copy to clipboard functionality

Let’s see how we can add this functionality:

Step 1:

Create a HTML with a paragraph having some content and button to click. You can use any relevant element instead of paragraph for example textbox, textarea, hidden fields etc.

<body>
    <p id="txt_knoband">KnowBand boasts of the best in the industry plugins for eCommerce systems and has years of experience working with eCommerce websites.</p>
    <button onclick="onClickCopy()">Copy Text</button>
</body>

Step 2:

You will need to create a function onClickCopy() which will copy the data of the paragraph. Function will simply run “document.execCommand(“copy”)” to copy the data to the clipboard.

function copyOnClick() {
    var tempInput = document.createElement("input");
    tempInput.value = document.getElementById("txt_knoband").innerHTML;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);
    alert("value copied");
}

In the last line of the script, we have simply added an alert action to inform the user that the data has been copied.

So finally when you click on the button “Copy Text”, data will be copied to the clipboard and you can simply paste by using CRTL + V.

Related Article: How to set Cookie using JavaScript

Sunny Saurabh

Sunny Saurabh

Sunny Saurabh is an experienced Software engineer in C# and ASP.NET as well as an expert as a PHP developer. He has also expert in database design, server maintenance and security. He has achieved this goal only in the short span of 3yrs and still looking forward to achieving more in the IT industry. He lives in New Delhi and his hobby to write the technical writeups.

Leave a Reply

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