JavaScript Clipboard API Programming Tutorial

Published :
Author :
Adam Khoury

Learn to use the JavaScript clipboard API in various ways that developers might use it in their projects.

Copy data from code elements containing rich text code. <style> code{ border: 1px solid #777; padding: 20px; width: 100%; display: block; } </style> <script> function copyToClipboard() { const mydata = document.getElementById("codebox1").innerHTML; const copybtn1 = document.getElementById("copybtn1"); const preserver = document.createElement("textarea"); preserver.innerHTML = mydata; navigator.clipboard.writeText(preserver.value); copybtn1.innerHTML += " &check;"; } </script> <code id="codebox1">&lt;div&gt;Hello Ladies!&lt;/div&gt;</code> <button id="copybtn1" onclick="copyToClipboard()">Copy to Clipboard</button> Copy data from textareas or text inputs. <script> function copyToClipboard() { const mydata = document.getElementById("text1").value; navigator.clipboard.writeText(mydata); copybtn1.innerHTML += " &check;"; } </script> <textarea id="text1">Howdy doody!</textarea> <br> <button id="copybtn1" onclick="copyToClipboard()">Copy to Clipboard</button> Write to the user clipboard. <script> // Write to the user clipboard navigator.clipboard.writeText("<b>Howdy, partner!</b>"); </script>