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?
Stay up to date with my weekly coding tips!
Walter G. is a software engineer, startup co-founder, former CTO of several tech companies and currently teaches programming for a coding bootcamp. He has been blogging for the past 5 years and is an avid BMX rider, bio-hacker
and performance enthusiast.