JavaScript Example | Copy Content to Clipboard

This javascript example code shows us how to copy the text content to the clipboard.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <textarea id="textId">Some copying text</textarea>
    <button id="copyBtn">Copy Button</button>
    <script>
      document.getElementById("copyBtn")
        .onclick = function() {
          let text = document.getElementById("textId").value;
          navigator.clipboard.writeText(text)
            .then(() => {
              alert('Text copied to clipboard');
            })
            .catch(err => {
              alert('Error in copying text: ', err);
            });
        }
    </script>
  </body>
</html>