Copying and pasting text with a click of a button is a common requirement in many web applications. While we usually take this basic functionality for granted, making it happen programmatically requires a bit of JavaScript code.

In this comprehensive guide, we will explore the different options available for copying text to clipboard in JavaScript.

Why Copy Text to Clipboard in JavaScript?

Here are some common use cases where copying text to clipboard comes in handy:

  • Allowing users to copy shareable content or codes from your web app interface with one click
  • Implementing "Copy to Clipboard" buttons for code snippets, URLs, etc.
  • Building browser extensions that need to copy data to clipboard
  • Automating repetitive copy-paste tasks for users

Doing these manually would require users to select the text, right click to bring up the context menu, and click copy.

This can be especially painful on mobile devices. With JavaScript, we can detect clicks and copy text to clipboard programmatically with fewer clicks.

Overall, it leads to a smoother user experience.

Approach 1: Using document.execCommand(‘copy‘)

One of the easiest ways to copy content to clipboard is by using the document.execCommand() method.

Here is a basic example:

function copyToClipboard(text) {
  const textField = document.createElement(‘textarea‘)

  textField.innerText = text
  document.body.appendChild(textField)
  textField.select()

  document.execCommand(‘copy‘)
  textField.remove()
}

copyToClipboard(‘Hello World‘) // Copies "Hello World" to clipboard

Here is what it does:

  1. Creates a temporary textarea element
  2. Sets the value as the text to copy
  3. Appends it to DOM so it gains focus automatically
  4. Selects the text
  5. Executes the copy command
  6. Removes the element

The key things to note are:

  • We create a textarea because the copy command works on selectable input elements
  • We append it to the DOM and remove later so it does not mess up the UI
  • The execCommand(‘copy‘) handles the copying itself behind the scenes

Benefits:

  • Simple, concise way to copy text
  • Well supported in all modern browsers

Drawbacks:

  • Older browsers may lack support
  • Only works on selectable input element types
  • Does not work on IE11 and below

So while this works great in most cases, it is not reliably cross-browser.

Next up, we‘ll see more robust techniques that work across browsers.

Approach 2: Using the Clipboard API

The Clipboard API provides programmatic access to the system clipboard.

It lets us read and write text from the clipboard using simple asynchronous JavaScript functions. Theclipboard contents persist even after navigating to other pages or closing the tab.

Here is an example usage:

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text)
    console.log(‘Content copied to clipboard‘)
  } catch (err) {
    console.error(‘Failed to copy: ‘, err)
  }
}

copyToClipboard(‘Hello World‘) 
  .then(() => {
    console.log(‘Copied content‘)  
  })

The key points are:

  • We use the navigator.clipboard.writeText() method to copy text
  • It returns a Promise so we can handle success and failure scenarios
  • Requires a secure context (HTTPS) in some browsers

Benefits:

  • Asynchronous, non-blocking
  • Separate permissions for reading and writing
  • Follows latest web standards

Drawbacks:

  • Browser support is still emerging
  • Requires Promise knowledge
  • HTTPS requirement can be limiting

The Clipboard API certainly looks very promising. However, due to its recent introduction, browser coverage can be patchy.

Let‘s look at some polyfill options next…

Approach 3: Using a JavaScript Polyfill

Since the Clipboard API does not have full browser coverage yet, we can use a JavaScript polyfill to standardize behavior across browsers.

Some popular ones are:

These handle inconsistencies and provide a unified API in older browsers.

For example, clipboard.js usage looks like:

import ClipboardJS from ‘clipboard‘; 

const clipboard = new ClipboardJS(‘.btn‘);

clipboard.on(‘success‘, e => {
  console.info(‘Text copied!‘);

  e.clearSelection();
});

Where .btn is the class selector for the copy button.

This abstracts away the browser differences and provides methods like:

  • on() to define callbacks
  • off() to detach them
  • destroy() to free up resources

The polyfill does the heavy lifting based on the environment.

Benefits:

  • Handles cross browser differences
  • Fallback mechanisms for older browsers
  • Lightweight, reusable logic
  • Actively maintained projects

Bonus: Copy to Clipboard on Button Click

Let‘s put it all together in a simple copy to clipboard demo.

We will:

  • Create a text input and copy button
  • Initialize ClipboardJS on button
  • Log success and failure callbacks

Here is the full code:

<!-- index.html -->

<input id="input" value="Hello World" />

<button 
  class="btn"
  data-clipboard-target="#input"
>
  Copy Text
</button>

<script type="text/javascript">

  import ClipboardJS from ‘./clipboard.min.js‘;

  const clipboard = new ClipboardJS(‘.btn‘);

  clipboard.on(‘success‘, e => {
    console.info(‘Copied text:‘, e.text);  
  })

  clipboard.on(‘error‘, e => {
    console.error(‘Unable to copy text:‘, e);
  })  

</script>

Key things to note:

  • We import ClipboardJS and initialize new instance
  • The data-clipboard-target attribute binds with #input
  • We define callbacks for success and failure scenarios

And that‘s it! Our copy to clipboard functionality is ready.

Here is a CodePen demo:

See the Pen
Copy to Clipboard Button | ClipboardJS
by CodeBucks (@codebucks)
on CodePen.

And we have successfully implemented copy to clipboard on button click!

The same logic can be enhanced and integrated across web apps based on requirements.

Wrapping Up

Copying content to clipboard is a common need across many web applications. In this post we explored different options available to do this in JavaScript:

  • document.execCommand(‘copy‘) – Simple but limited browser support
  • Clipboard API – Modern method but requires polyfills
  • JavaScript Libraries – ClipboardJS to handle cross browser differences

The option you pick depends on your specific requirements and browser coverage needs.

I hope this post gives you a firm grounding on how to easily copy text to clipboard using JavaScript. Let me know if you have any other cool ideas to share!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *