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.
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
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.
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.
Did you find this article helpful?
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.