Following is the code to copy text to the clipboard with JavaScript −
Example
<!DOCTYPE html>
<html>
<head>
<style>
button {
border: none;
outline: none;
background-color: rgb(191, 187, 255);
color: black;
font-weight: bold;
padding: 10px;
}
input {
padding: 10px;
}
</style>
</head>
<body>
<h1>Clipboard example</h1>
<h2>Click the button below to copy text and paste it somewhere</h2>
<input type="text" value="Hello World" class="textInput" />
<button class="copy">Copy text</button>
<script>
document.querySelector(".copy").addEventListener("click", copyText);
function copyText() {
var copyText = document.querySelector(".textInput");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
alert("The copied text is: " + copyText.value);
}
</script>
</body>
</html>Output
This will produce the following output −

On clicking the ‘Copy text’ button −
