How To Copy Text To Clipboard Using JavaScript
The following example shows, how to copy text from a input to the clipboard with JavaScript.
Example 1
<input type="text" value="Hello World" id="txtInput"> <input type='button' onclick="funCopy(this)" id="btnCopy" value='Copy text'> <script> function funCopy(ele) { var txt_input = document.querySelector("#txtInput"); //access the system clipboard and write text to it navigator.clipboard.writeText(txt_input.value); ele.value="Text Copied"; } </script>Try it Yourself
The following example shows, how to copy text from a div to clipboard with JavaScript.
Example 2
<input type='button' onclick="copyClipboard(this)" id="btnCopy" value='Copy text' /> <div id='divBox'> The red line moved across the page. With each millimeter it advanced forward, something changed in the room. The actual change taking place was difficult to perceive, but the change was real. The red line continued relentlessly across the page and the room would never be the same. </div> <script> function copyClipboard(ele) { var copyElement = document.querySelector("#divBox"); //Internet Explorer if(document.body.createTextRange) { var txtRange = document.body.createTextRange(); txtRange.moveToElementText(copyElement); txtRange.select(); document.execCommand("Copy"); ele.value='Copied'; } //Other Browsers else if(window.getSelection) { var selection = window.getSelection(); var txtRange = document.createRange(); txtRange.selectNodeContents(copyElement); selection.removeAllRanges(); selection.addRange(txtRange); document.execCommand("Copy"); ele.value='Copied'; } } </script>Try it Yourself