DEV Community

Saravana Kumar Putta Selvaraj
Saravana Kumar Putta Selvaraj

Posted on

2

JS:Snippets — Copy text to the clipboard using javascript in 5 minutes.

In this article, we are going to build the functionality of copying the text to the clipboard using javascript in 5 minutes.

HTML STRUCTURE

<div>
  <input type="text" id="text" placeholder="Enter text"/>
  <button onClick="copyTextToClipBoard()">Copy To ClipBoard</button>
</div>
Enter fullscreen mode Exit fullscreen mode

JS Function

function copyTextToClipBoard(){
  //Input Element with id "text"
  let textToBeCopied = document.getElementById('text');
  //Select the content in the input element
  textToBeCopied.select();
  textToBeCopied.setSelectionRange(0, 99999);
  //copy the text inside the input element to clipboard
  document.execCommand('copy');
  alert('Text copied to Clipboard');
}
Enter fullscreen mode Exit fullscreen mode

Buit-in Functions used

select
setSelectionRange
execCommand

Full code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy Text 2 Clipboard</title>
</head>
<body>
<div>
<input type="text" id="text" placeholder="Enter text" />
<button onClick="copyTextToClipBoard()">Copy To ClipBoard</button>
</div>
<script>
function copyTextToClipBoard() {
//Input Element with id "text"
let textToBeCopied = document.getElementById('text');
//Select the content in the input element
textToBeCopied.select();
textToBeCopied.setSelectionRange(0, 99999);
//copy the text inside the input element to clipboard
document.execCommand('copy');
alert('Text copied to Clipboard');
}
</script>
</body>
</html>

Codepen

This article is made with ❤️. Please let me know what content you want me to write. Always for you.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay