home ~ projects ~ socials

Copy Selected Text To The System Copy/Pasteboard

HTML

<button class="copyButton">Copy</button>

Output

JavaScript

const copyButtonEl = document.querySelector(".copyButton")

copyButtonEl.addEventListener('click', copySelection)

async function copySelection(event) {
  try {
    const selection = document.getSelection();
    const selectedText = selection.toString();
    await navigator.clipboard.writeText(
      selectedText
    )
    console.log("Selection copied.")
  } catch (err) {
    console.error("Could not copy selection to clipboard")
  }
}
-- end of line --