How to copy text with ease in JavaScript using the Clipboard API

Copying text especially code snippets or API key from web pages is a herculean task and I know a lot of developers would find the process of selecting a combination of the CTRL or CMD key with the C key boring. This even gets more tasking when the snippet span through several lines.

I implemented the copy to clipboard feature on this site to improve your experience while reading my articles. In this article, I'll write about how I achieved this.

I created this feature using the Clipboard API which is available on the navigator.clipboard object. According to Can I Use, the Clipboard API is supported by major browsers and writing to the clipboard is available through user-initiated event callbacks like a click.

Handling a code block

Given the code,

function stripHTML(code) {
  return code.replace(/(<([^>]+)>)/gi, '');
}

You need to add a copy functionality to make users aware that they can copy the code snippet.

<span class="copy">Copy</span>

To mitigate errors, you need to check for the availability of the Clipboard API before usage:

if (!navigator.clipboard) {
  // Clipboard API is not available
  return;
}

Then, add a click event listener to the Copy text:

document.querySelector('.copy').addEventListener('click', async event => {
  if (!navigator.clipboard) {
    // Clipboard API is not available
    return;
  }
});

To copy the snippet to the Clipboard, grab the innerText of the element

const codeBlock = document.querySelector('.code').innerText;

Call the navigator.clipboard.writeText() method afterwards in a try/catch block to handle unforeseen errors. This yields the code:

document.querySelector('.copy').addEventListener('click', async event => {
  if (!navigator.clipboard) {
    // Clipboard API is not available
    return;
  }
  try {
    const codeBlock = document.querySelector('.code').innerText;

    await navigator.clipboard.writeText(codeBlock);
    event.target.textContent = 'Copied to clipboard';
  } catch (err) {
    console.error('Failed to copy!', err);
  }
});

Handling multiple code blocks

To attach the click event on multiple code elements, add the same class to the elements and call querySelectorAll() on the elements, then use forEach() to iterate over them.

document.querySelectorAll('.code').forEach(item => {
  item.addEventListener('click', async event => {
    if (!navigator.clipboard) {
      // Clipboard API is not available
      return;
    }
    try {
      await navigator.clipboard.writeText(event.target.innerText);
    } catch (err) {
      console.error('Failed to copy!', err);
    }
  });
});

Conclusion

The ability to copy text to the clipboard with a single button click is an essential feature in web pages. I hope this helps.

View the single clipboard content and multiple clipboard contents on Codepen.

Article Tag  JavaScript

Share this article:

Stay Updated

    More Articles


    I write about accessibility, performance, JavaScript and workflow tooling. If my articles have helped or inspired you in your development journey, or you want me to write more, consider supporting me.