How can I use JavaScript to copy text to the clipboard across multiple browsers?

I’m looking for a reliable way to javascript copy to clipboard that works in different environments. Also, how does Trello access the user’s clipboard for similar functionality?

You can use the Clipboard API (Modern Browsers) :

function copyToClipboard() {
  const text = "Text to copy";
  navigator.clipboard.writeText(text).then(() => {
    console.log('Text successfully copied!');
  }).catch(err => {
    console.error('Failed to copy text: ', err);
  });
}

This method uses the modern Clipboard API, which is the most reliable for modern browsers. It’s simple and doesn’t require external libraries. Just make sure the site is served over HTTPS, as some browsers require it for clipboard access.

The solution given by @raimavaswani works good but instead of API this is what I did you resolve the same issue I faced I used document.execCommand() for Legacy Support

Below is the method :

function copyToClipboard() {
  const text = "Text to copy";
  const textArea = document.createElement('textarea');
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  document.execCommand('copy');
  document.body.removeChild(textArea);
  console.log('Text successfully copied!');
}

This works well for browsers that don’t yet fully support the Clipboard API (like some older versions of IE). It’s a bit of a workaround, but it still works reliably.

Hey both of your answers are really, helpful but would just like to add about the extra library .

Using Clipboard.js Library (If You Need Extra Features)

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js"></script>

<button id="copy-btn" data-clipboard-text="Text to copy">Copy</button>

<script>
  new ClipboardJS('#copy-btn');
</script>

For projects that need additional clipboard functionality and cross-browser support, this library offers a clean, easy-to-use API and handles edge cases well.