- How to copy text to the clipboard with Javascript
- Boilerplate
- Method 1: execCommand(‘copy’)
- Method 2: Clipboard API
- UPDATE: Copy to clipboard with Vue 3 directive
- How to Copy Text to the Clipboard with HTML and JavaScript
- Copying Text From a Text Box to the Clipboard Using JavaScript
- Demo:
- HTML Code
- JavaScript Code
- How to Copy Any Text By Creating a Selection Range in JavaScript
- Demo:
- HTML Code
- Javascript Code
- How to Copy Text To the Clipboard that Isn’t Visible with HTML
- Demo:
- HTML Code
- JavaScript Code
- Read More From Actual Wizard
- Primary Sidebar
- More posts from this section
- How to Copy Text to the Clipboard with JavaScript
- How to Check the Browser’s Permissions
- How to Copy Text to the Clipboard
- Copy text to clipboard example
- Wrapping Up
How to copy text to the clipboard with Javascript
Copying data from the browser into your clipboard is a small feature, yet a quite powerful one. No more manual selecting & crtl + c does save a bit of time when following larger coding articles. I’ve just added the small clipboard sign next to all my snippets for a reader’s convenience myself. Read on to find out how I did it.
Boilerplate
Create an index.html file, as well as a main.js file in a directory of your choice. Fill the index — file up with the following and let’s jump in.
lang="en"> charset="UTF-8" /> http-equiv="X-UA-Compatible" content="IE=edge" /> name="viewport" content="width=device-width, initial-scale=1.0" /> Copy to clipboard With textarea placeholder="Write your content here and press 'Copy Text'" id="clipboard-area" cols="30" rows="2" > placeholder="Paste your content here" cols="30" rows="2" > style="width: 260px" onclick="handleCopyTextFromArea()"> Copy text Without textarea style="display: flex"> style="width: 260px; margin: 0"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. placeholder="Paste your content here" cols="30" rows="2" > style="width: 260px" onclick="handleCopyTextFromParagraph()"> Copy text src="main.js">
We’ll have two functions attached to the buttons — handleCopyTextFromArea and
handleCopyTextFromParagraph — let’s fill them with life.
Method 1: execCommand(‘copy’)
While the functionality of this method is deprecated according to MDN docs, it still works well with a textarea — html tag. And even if you do not have such available, creating it — and filling its value with the desired text content — is done very quickly. If you have a text area available, add the following to your index.html
function handleCopyTextFromArea() const area = document.querySelector('#clipboard-area') area.select(); document.execCommand('copy') >
- Create the textarea element and add it to the DOM.
- Populate its value with the text from the paragraph — or any other element.
- Use the above execCommand(‘copy’) — method to copy the textual content
- Remove the element again.
function handleCopyTextFromParagraph() const body = document.querySelector('body'); const paragraph = document.querySelector('p'); const area = document.createElement('textarea'); body.appendChild(area); area.value = paragraph.innerText; area.select(); document.execCommand('copy'); body.removeChild(area); >
If you now try and crtl + v into the textarea to the right, you should see the input being pasted. While this approach does still work very well, modern browsers have implemented their own interfaces to take care of clipboard features. Let’s take a look at that next.
Method 2: Clipboard API
The clipboard API is a modern, promise based approach that solely focuses on the clipboard instead of doing many things at once. It requests you for permission and works only over https, making it more secure by design. According to Can I use, older browsers do not support this functionality, therefor you might want to consider having the alternative in place as well.
Let’s replace the above handleCopyTextFromParagraph function with the following:
function handleCopyTextFromParagraph() const cb = navigator.clipboard; const paragraph = document.querySelector('p'); cb.writeText(paragraph.innerText).then(() => alert('Text copied')); >
And that’s about it, really. You might want to replace the .then() — callback with some neater type of user feedback and check for user permission, still — goal achieved — the text is available and ready to be parsed.
UPDATE: Copy to clipboard with Vue 3 directive
If you’re using Vue.js to build your application, you can wrap the above function using a Vue custom directive. Then, you achieve the same functionality by clicking on (or interacting in any other way with) the component that has v-clip bound to it.
Declare the following function inside of you main.js file and have it registered globally after creating the Vue app:
const vClip = // For Vue 2, you can use bind instead of mounted mounted: (el) => el.addEventListener('click', () => const cb = navigator.clipboard; // Check if the clicked on element is an input element const input = el.tagName === 'input' ? el : el.querySelector('input'); // Copy the text to clipboard cb.writeText(input.value).then(() => alert('Text copied')); >); >, >; // Create the app and mount it const app = createApp(App); app.directive('clip', vClip); app.mount('#app');
Then, assuming you have the following component:
label="Short link:" v-model="form.result" disabled />
You can add the v-clip directive to it:
label="Short link:" v-clip v-model="form.result" disabled />
How to Copy Text to the Clipboard with HTML and JavaScript
Having a click-able button on your website that allows users to copy text can be easily achieved by using the document.execCommand() method.
Unfortunately support for the execCommand() method is lacking in many old browsers, such as Opera Mini and the UC Browser for Android.
The vast majority of users should be able to copy the text with out any issues and the website can display an error message if the copy command fails.
Additionally to work around browser support problem: As long as we put the text into a text box, it should be easy enough for users using these browsers to manually copy the text to the clipboard.
Copying Text From a Text Box to the Clipboard Using JavaScript
Demo:
HTML Code
JavaScript Code
After pressing the button, you should be able to paste the text into the text field below or in any other application that will accept text being pasted from the clipboard.
Here is a box that you can paste the text into so you don’t have to leave this page:
Unfortunately, due to security concerns, it is not possible to paste text using JavaScript into a browser window through JavaScript, unless it’s a background page of a browser extension. This is to prevent websites from gathering sensitive information such as user passwords.
There is also one big issue with this code, if the user currently has text selected, they will lose their selection. In the following examples, the code will restore the user’s previous text selection if they had one.
How to Copy Any Text By Creating a Selection Range in JavaScript
Since selecting all of the text in a text box using select() will only work with a text box, if you want to copy all text to the clipboard of a specific ID or class name, you will have to create a text selection range instead.
This is a little bit more flexible as you do not have to have a text box.
Demo:
HTML Code
The text to copy to the clipboard.
Javascript Code
How to Copy Text To the Clipboard that Isn’t Visible with HTML
This is probably the most useful version of the script as it allows you to generate text in JavaScript, which is not visible on the page at all, then place that text on to the clipboard.
It works by creating an element that is off the screen with the text that is to be copied.
Since browser compatibility could be an issue, the script will also display an error message in a message box if it can’t copy the text. Using a message box isn’t the best way to handle this but you can customize the code to display the error notification any way you choose.
Demo:
Copy Some Text That You Can’t See!
HTML Code
JavaScript Code
I really hope that you enjoyed this tutorial!
Read More From Actual Wizard
An email address has four parts; the recipient name, the @ symbol, the domain name, and the top-level domain. …
There are a number of different ways to get the last element of an array in JavaScript. Below we will explore …
How to use document.write() in JavaScript The document.write() function is commonly used when testing simple …
Opening a new browser window in a new tab can be done easily in JavaScript. Modern web browsers provide a …
Primary Sidebar
More posts from this section
Copyright © 2023 ActualWizard.com
How to Copy Text to the Clipboard with JavaScript
Joel Olawanle
When you’re building advanced web pages and applications, you’ll sometimes want to add the copy feature. This lets your users simply click a button or icon to copy text rather than highlighting the text and clicking a couple of buttons on the keyboard.
This feature is mostly used when someone needs to copy an activation code, recovery key, code snippet, and so on. You can also add functionalities like an alert or text on the screen (which could be a modal) to inform the user that the text has been copied to their clipboard.
Previously you would’ve handled this with the document.execCommand() command, but that is deprecated (no longer recommended). You can now use the Clipboard API, which allows you to respond to clipboard commands (cut, copy, and paste) and asynchronously read from and write to the system clipboard.
In this article, you will learn how to write (copy) text and images to the clipboard with the Clipboard API.
In case you are in a rush, here is the code:
Hello World
If you are not in a rush, let’s understand more about the Clipboard API and see how this works with a demo project.
How to Check the Browser’s Permissions
It is important to know that the Clipboard API is only supported for pages served over HTTPS. You should also check for browser permissions before attempting to write to the clipboard to verify if you have the write access. You can do this with the navigator.permissions query:
navigator.permissions.query(< name: "write-on-clipboard" >).then((result) => < if (result.state == "granted" || result.state == "prompt") < alert("Write access granted!"); >>);
How to Copy Text to the Clipboard
To copy text with the new Clipboard API, you will use the asynchronous writeText() method. This method accepts only one parameter — the text to copy to your clipboard. This can be a string, a template literal holding variables and other strings, or a variable used to hold a string.
Since this method is asynchronous, it returns a promise. This promise is resolved if the clipboard has been updated successfully, and is rejected otherwise:
navigator.clipboard.writeText("This is the text to be copied").then(() => < console.log('Content copied to clipboard'); /* Resolved - text copied to clipboard successfully */ >,() => < console.error('Failed to copy'); /* Rejected - text failed to copy to the clipboard */ >);
You can also use async/await alongside try/catch:
async function copyContent() < try < await navigator.clipboard.writeText('This is the text to be copied'); console.log('Content copied to clipboard'); /* Resolved - text copied to clipboard successfully */ >catch (err) < console.error('Failed to copy: ', err); /* Rejected - text failed to copy to the clipboard */ >>
Copy text to clipboard example
Here is a demo showing how it works using a real-life example. In this example, we’re fetching quotes from a public quote API. Then when you click the copy icon, the quote and its author get copied, showing that you can adjust what you copy into the writeText() method.
See the Pen copy text JS by Olawanle Joel (@olawanlejoel) on CodePen.
Wrapping Up
In this article, you have learned how to copy text to the clipboard with JavaScript using the Clipboard API without having to think outside the box or install any JavaScript library.
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.