DEV Community

Cover image for Creating copy button with JS
Walter Nascimento
Walter Nascimento

Posted on

Creating copy button with JS

[Clique aqui para ler em português]

It is quite common that we need to copy something on the screen, either to search later or just to save somewhere, and with that, we will create a quick function to copy text with JavaScript.

Code

First we will create the interface, we will do something simple, using only HTML.

<input id="input" type="text" />
<button id="execCopy"> execCopy </button>
<button id="clipboardCopy"> clipboardCopy </button>
Enter fullscreen mode Exit fullscreen mode

In the HTML structure, an input was created that will be the text to be copied, and we have two buttons, which will be used to demonstrate two ways to copy text with JavaScript.

// Type 1
document.getElementById('execCopy').addEventListener('click', execCopy);
function execCopy() {
  document.querySelector("#input").select();
  document.execCommand("copy");
}

// Type 2
document.getElementById('clipboardCopy').addEventListener('click', clipboardCopy);
async function clipboardCopy() {
  let text = document.querySelector("#input").value;
  await navigator.clipboard.writeText(text);
}
Enter fullscreen mode Exit fullscreen mode

In the first type we add an event to the button with id execCopy that calls a function of the same name, in this function we first select the text, and then we use the execCommand("copy"); function; this is a native function that executes the copy command.

In the second type we add an event to the button with id clipboardCopy that calls a function of the same name, in this function we first retrieve the input value and then we move to the clipboard function, a detail in this function is that to work correctly it is necessary to use async and await, or use then(), as it is a promise.

ready as simple as that.

Demo

See the complete project working below.

Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Top comments (0)