Information



Tags



Share

How to create a copy to clipboard button in JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



Definition

If you want to improve the user experience on your website, you should implement a copy to clipboard button on the user dashboard, especially if it provides information to be used on other sections. In this tutorial, I shall show you how to copy an inline text on the page by using plain and simple JavaScript.

Code

To copy a text to the clipboard, first of all, we need an input element.

Nevertheless, we can create a temporary one in JavaScript as shown below if we want to copy index in a not-input element.

After getting the index of the text_to_copy, create an input element by using document.createElement("INPUT").

And, change the value of the temporary input element as the index.

Append child to the body and select it by using the select() method.

After this step, run the execCommand(“copy”) method to copy the selected text to the clipboard.

Remove the temporary input element.

I used an event listener to activate the function but: you can use the onclick method instead of it.


var text_to_copy = document.getElementById("text_to_copy").innerHTML;
var copy_button = document.getElementById("copy_button");

copy_button.addEventListener("click", function(){
var temp = document.createElement("INPUT");
temp.value = text_to_copy;
document.body.appendChild(temp);
temp.select();
document.execCommand("copy");
temp.remove();
alert("Text Copied!");
});

Result:

This is the example text in a not-input element to be copied.