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>
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');
}
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.
Top comments (0)