DEV Community

Basha
Basha

Posted on

How to copy text to your clipboard in JavaScript?

Hello:)
It is quite easy to copy text to clipboard using JavaScript.

function copy(text){
  const text_ = document.createElement('textarea');
  text_.setAttribute('readonly', '');
  text_.value = text
  document.body.appendChild(text_);
  textbox.select();
  document.execCommand('copy');
  textbox.parentNode.removeChild(text_)
}
Enter fullscreen mode Exit fullscreen mode

This function should copy whatever you pass in the parameter.

Examples:
This will let you copy hello world

function copy(text){
  const text_ = document.createElement('textarea');
  text_.setAttribute('readonly', '');
  text_.value = text
  document.body.appendChild(text_);
  textbox.select();
  document.execCommand('copy');
   textbox.parentNode.removeChild(text_)
}

copy("Hello world")
Enter fullscreen mode Exit fullscreen mode

This will let you copy a string


function copy(text){
  const text_ = document.createElement('textarea');
  text_.setAttribute('readonly', '');
  text_.value = text
  document.body.appendChild(text_);
  textbox.select();
  document.execCommand('copy');
   textbox.parentNode.removeChild(text_)
}
var text_var = "This is some words stored in a string"
copy(text_var)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)