Html onclick copy text

Complete code with Copy/Paste πŸŽ‰β­βœ¨

A Skilled Software Engineer πŸš€ from India. Always working on some project or learning something new! Want to become a full-time Freelancer πŸ’Έ and an Open Source Contributor ❀️.

More from Dhiman_aman

Once suspended, raynecoder will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, raynecoder will be able to comment and publish posts again.

Once unpublished, all posts by raynecoder will become hidden and only accessible to themselves.

If raynecoder is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Dhiman_aman.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag raynecoder:

raynecoder consistently posts content that violates DEV Community’s code of conduct because it is harassing, offensive or spammy.

Unflagging raynecoder will restore default visibility to their posts.

DEV Community β€” A constructive and inclusive social network for software developers. With you every step of your journey.

Built on Forem β€” the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community Β© 2016 — 2023.

We’re a place where coders share, stay up-to-date and grow their careers.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

How to Copy Text to the Clipboard with JavaScript

Joel Olawanle

Joel Olawanle

How to Copy Text to the Clipboard with JavaScript

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.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

How TO — Copy Text to Clipboard

Learn how to copy text to the clipboard with JavaScript.

Click on the button to copy the text from the text field.

Copy Text to Clipboard

Step 1) Add HTML:

Example

Step 2) Add JavaScript:

Example

function myFunction() <
// Get the text field
var copyText = document.getElementById(«myInput»);

// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices

// Copy the text inside the text field
navigator.clipboard.writeText(copyText.value);

// Alert the copied text
alert(«Copied the text: » + copyText.value);
>

Display Copied Text in a Tooltip

Example

.tooltip <
position: relative;
display: inline-block;
>

.tooltip .tooltiptext visibility: hidden;
width: 140px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -75px;
opacity: 0;
transition: opacity 0.3s;
>

.tooltip .tooltiptext::after content: «»;
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
>

.tooltip:hover .tooltiptext visibility: visible;
opacity: 1;
>

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

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.

Π§ΠΈΡ‚Π°ΠΉΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅:  Php Π·Π°Π³Ρ€ΡƒΠ·ΠΈΡ‚ΡŒ Ρ„Π°ΠΉΠ» ΠΊΠ»ΠΈΠ΅Π½Ρ‚Ρƒ

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

Copyright Β© 2023 ActualWizard.com

Π§ΠΈΡ‚Π°ΠΉΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅:  Java annotation parameter types

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

How to Copy Text to the Clipboard with JavaScript

Joel Olawanle

Joel Olawanle

How to Copy Text to the Clipboard with JavaScript

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.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ

ΠžΡ†Π΅Π½ΠΈΡ‚Π΅ ΡΡ‚Π°Ρ‚ΡŒΡŽ