How to copy variable value to clipboard with one click?

We will be using the document.execCommand() method.

Get coding with the HTML below and we will be writing copyFunction() later.

<div class="box">
  <p id="text">Text to copy</p>
  <button id="copyButton" onclick="copyFunction()">Copy</button>

Add the CSS for a nicer look:

  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: 'Calibri';
  font-size: 1em
  text-align: center;
  padding: 20px
  border: none;
  background-color: darkslategrey;
  color: white;
  padding: 20px;
  font-size: .9em

Now onto the Javascript. On button click, we have called copyFunction():

function copyFunction(){


Inside the curly brackets, we can start off by assigning the text inside <p> to the variable text:

let text = document.getElementById('text').innerHTML;

Then we need to create a <textarea> and make text its value:

let dummy = document.createElement('textarea');
dummy.value = text;

After  appending it to <body>, we can use select() method to select the text inside it:


Now we can replace the content in our clipboard with the selection:


And then of course we have to remove dummy from our document:


That’s it, and you can visit here for the complete code and a demo.