More articles

How to copy to clipboard in JavaScript

Written by
Filed under
Published on

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.

The process is relatively simple and just requires a couple of lines of JavaScript to get it up and running.

1. Create an input field

The first thing that you'll need is a text input box with a few attributes. Mainly just the type set to "text" and an id value. This would also work 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 methods focus() and select() in order to highlight the given text in the input field. While most browsers will automatically focus() on an element when calling select(), it is a safer practice to include the focus() method call just to be safe.

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

	// focus on the element

	// Select the text field;

  	// Copy the text inside the text field

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 (assuming they are 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 example we used 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.

Happy coding!

Walter Guevara is a Computer Scientist, software engineer, startup founder and currently mentors for a coding bootcamp. He has been creating software for the past 15 years.

Discussion / Comments / Questions

No messages posted yet

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment