How to Copy Text to the Client's Clipboard Using Jquery

Click button copy to clipboard

Edit as of 2016

As of 2016, you can now copy text to the clipboard in most browsers because most browsers have the ability to programmatically copy a selection of text to the clipboard using document.execCommand("copy") that works off a selection.

As with some other actions in a browser (like opening a new window), the copy to clipboard can only be done via a specific user action (like a mouse click). For example, it cannot be done via a timer.

Here's a code example:

document.getElementById("copyButton").addEventListener("click", function() {    copyToClipboard(document.getElementById("copyTarget"));});
function copyToClipboard(elem) { // create hidden text element, if it doesn't already exist var targetId = "_hiddenCopyText_"; var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; var origSelectionStart, origSelectionEnd; if (isInput) { // can just use the original source element for the selection and copy target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else { // must use a temporary form element for the selection and copy target = document.getElementById(targetId); if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target); } target.textContent = elem.textContent; } // select the content var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // copy the selection var succeed; try { succeed = document.execCommand("copy"); } catch(e) { succeed = false; } // restore original focus if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // restore prior selection elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // clear temporary content target.textContent = ""; } return succeed;}
input {  width: 400px;}
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br><input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">

how can i copy text from textbox to clipboard using jquery/javascript/html5

There is some jQuery plugins like:

http://www.steamdev.com/zclip/

http://archive.plugins.jquery.com/project/clipboard

How do I copy to the clipboard in JavaScript?

Overview

There are three primary browser APIs for copying to the clipboard:

  1. Async Clipboard API [navigator.clipboard.writeText]

    • Text-focused portion available in Chrome 66 (March 2018)
    • Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
    • Text can be copied to the clipboard directly from a variable.
    • Only supported on pages served over HTTPS.
    • In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
  2. document.execCommand('copy') (deprecated) /p>

    • Most browsers support this as of ~April 2015 (see Browser Support below).
    • Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
    • Text is read from the DOM and placed on the clipboard.
    • During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
  3. Overriding the copy event

    • See Clipboard API documentation on Overriding the copy event.
    • Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
    • Not covered here as it doesn't directly answer the question.

General development notes

Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard see below for more detail.

IMPORTANT (noted here 2020/02/20)

Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).

To develop create your own web page, serve that page over an HTTPS connection to test and develop against.

Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/

Async + Fallback

Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the document.execCommand('copy') method to get good browser coverage.

Here is a simple example (may not work embedded in this site, read "important" note above):

function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;

// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}

document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}

var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});

copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

</textarea>
</div>

Copy to clipboard with jQuery/js in Chrome

I just find another amazing repo on Github.

Modern copy to clipboard. No Flash. Just 3kb gzipped

https://github.com/zenorocha/clipboard.js

Browser Support:



Related Topics



Leave a reply



Submit