Let get started by setting up some HTML:
<input type="text" id="key-txt" value="1seWYeywqmTnqv7a5FC6LkD2vsdEx6jXOwqkmhLN" size="45" readonly /> <button id="key-btn">COPY</button>Code language: HTML, XML (xml)
Next we’ll add a click event listener to the button:
First we’re checking if the browser supports the
navigator.clipboard which is part of the Clipboard API that provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the clipboard. If the browser does support
navigator.clipboard the text is written to the clipboard.
That’s all for this tutorial, it should be noted that similar functionality could also be written using
document.execCommand() however that method is no longer recommended as browsers drop support for it.