Make A Button To Copy Text Onto The Clipboard

March 2022

lima delta november

JavaScript
const copyContent = async () => {
  try {
    await navigator.clipboard.writeText(
      content.innerText
    )
    copyButton.innerHTML = "Copied!"
  } catch (err) {
    console.error("Could not copy to clipboard")
  }
}

document.addEventListener("DOMContentLoaded", () => {
  copyButton.addEventListener("click", copyContent)
})

Notes

  • I'm using innerText instead of innerHTML in the copy. Using innerHTML put the tags themselves in the output when I posted into a plain-text editor
end of line