Javascript is a programming language that allows you to execute commands on your browser after it has loaded into the page. In this post, learn how to copy text from one part of the webpage into another using Javascript's clipboard API.
Here we are going to use bootstrap to design HTML components to reduce development time and focus on our main functionality, You can use your own CSS or just include the following bootstrap file in the head tag.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
1. Copy Text to Clipboard
HTML Code:
<body class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-8 col-sm-12 mb-3">
<input type="text" class="form-control" id="text" />
</div>
<div class="col-md-8 col-sm-12 mb-3">
<button class="btn btn-primary" onclick="copyText()">Copy</button>
</div>
<div class="col-md-6 col-sm-12 alert alert-warning alert-dismissible fade show d-none" id="alert" role="alert">
<span id="alert_text"></span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</body>
JavaScript Code:
function copyText()
{
//get input field text
const inputText = document.getElementById("text");
//copy text inside text field
navigator.clipboard.writeText(inputText.value);
//alerting copied text
document.getElementById("alert_text").innerHTML = "Copied Text : " + inputText.value;
document.getElementById("alert").classList.remove("d-none");
}