How to Copy Text to Clipboard
we use The copy to clipboard functionality many times daily. A very common need when building websites is the ability to copy text to clipboard with a single button click. Javascript can easily do this in short steps:
- create an
<input>
element to be appended to the document like this and add a Button where you can call your Javascript Function
<input type="text" value="Text to copy" id="myInput" />
<button onclick="copyWithOneClick()">Copy text</button>
Now in your Javascript Function :
- call the
getElementById()
method with your input ID in our case its "myInput" . - Use
HTMLInputElement.select()
to select the contents of the<input>
element. - Use
Document.execCommand('copy')
to copy the contents of the<input>
to the clipboard
your final Javascript function will look like this
function copyWithOneClick() {
var copyText = document.getElementById("myInput");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
}

You like our Content? Follow us to stay up-to-date.