Home Icon
Tags IconArchives Icon
How to copy variable value to clipboard with JavaScript?

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>
</div>
  

Add the CSS for a nicer look:

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

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:

  
document.body.appendChild(dummy)
dummy.select()
  

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

  
document.execCommand('copy')
  

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

  
document.body.removeChild(dummy)
  

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

© 2021 Fazeela Nizam