Menu

How to copy to clipboard in JavaScript

How to copy to clipboard in JavaScript

Sure you can always just highlight text and then ctrl+c, but sometimes due to text constraints (large text) or just for ease of use to your users, allowing them to quickly copy content with a single button click can be very helpful.

You can set up a quick copy and paste configuration as follows.

Now if you open Notepad (or your favorite text editor) and paste, you'll see your written text.

1. Create an input field

The first thing that you'll need is a text input box with a few attributes in place. Mainly just the type set to "text" and an id value. Note that this also works the same for the <textarea> element.

<input type="text" placeholder="enter some text" id="input1" class="form-control">
<button onclick="copyText()" class="btn">Copy text</button> 

2. copyText() function

We'll make use of the built-in JavaScript focus() and select() methods in order to highlight the given text in the input field dynamically. While most browsers will automatically focus() on an element when calling select(), it is a safer practice to include the focus() method just to be safe.

function copyText()
{
	let copyText = document.getElementById("input1");

	// focus on the element
	copyText.focus();

	// Select the text field
  	copyText.select();

  	// Copy the text inside the text field
  	document.execCommand("copy");
}

The actual copying to the clipboard happens with the execCommand() method, which I'll break down further below.

3. execCommand()

The execCommand(actionname) method can run commands against an editable region on a web page, such as the <input>, <textarea> and <div>'s (if a div, it must be set to contenteditable='true'). There are various action's that you can pass as an argument that will allow you to edit the content in these fields.

For this particular use case we should use the "copy" action, but you can perform other operations such as "paste", "undo", "redo", "underline" and "bold" to just name a few. For a full list of action items you can check out the MDN page right over here.

And there you have it. The copyText() function above is generic enough that you should include it in your own personal coding library for whenever the need arises.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet

Add a comment