Using execCommand (Javascript) to copy hidden text to clipboard
--Update--
Document.execCommand()
[1] Before Firefox 41, clipboard capability needed to be enabled in the user.js preference file. See A brief guide to Mozilla preferences for more information. If the command wasn't supported or enabled, execCommand was raising an exception instead of returning false. In Firefox 41 and later, clipboard capability is enabled by default in any event handler that is able to pop-up a window (semi-trusted scripts).
Since Firefox version 41 Document.execCommand() now works. So no need to use a fallback anymore.
Since browsers seem to behave differently when it comes to clipboard access,
it took me a while to get my head around it.
It's pretty similar to your solution, but the difference is to create a temporary element and fill it with the input value
. That way we can keep the input's display
property set to none
.
There is also a workaround for IE which uses window.clipboardData
.
Firefox would not let me access the clipboard at all. So I had to add a prompt
to let users manually copy the input value. Sure a prompt
is ugly, but you could just use a modal like a window, which would do the same.
Since this seems to be a knotty thing, I am on Win7 (64 bit) and tested in
Chrome - Version 43.0.2357.134 m
IE - Version 11.0.9600.17914
and Firefox is irrelevant because it would not let me access it anyway.
var copyBtn = $("#copy-btn"),
input = $("#copy-me");
function copyToClipboardFF(text) {
window.prompt ("Copy to clipboard: Ctrl C, Enter", text);
}
function copyToClipboard() {
var success = true,
range = document.createRange(),
selection;
// For IE.
if (window.clipboardData) {
window.clipboardData.setData("Text", input.val());
} else {
// Create a temporary element off screen.
var tmpElem = $('<div>');
tmpElem.css({
position: "absolute",
left: "-1000px",
top: "-1000px",
});
// Add the input value to the temp element.
tmpElem.text(input.val());
$("body").append(tmpElem);
// Select temp element.
range.selectNodeContents(tmpElem.get(0));
selection = window.getSelection ();
selection.removeAllRanges ();
selection.addRange (range);
// Lets copy.
try {
success = document.execCommand ("copy", false, null);
}
catch (e) {
copyToClipboardFF(input.val());
}
if (success) {
alert ("The text is on the clipboard, try to paste it!");
// remove temp element.
tmpElem.remove();
}
}
}
copyBtn.on('click', copyToClipboard);
#copy-me {
display:none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="Element To Be Copied" id="copy-me" value="foo loves bar"/>
<button id="copy-btn">Copy</button><br/><br/>
<textarea placeholder="paste here"></textarea>
Hidden element won't copy to clipboard
Instead of the hidden
attribute, use an offscreen class and the aria-hidden
attribute (the latter for accessibility):
.offscreen {
position: absolute;
left: -999em;
}
<input ... class="offscreen" aria-hidden="true">
How Can I Copy Text From Hidden Textarea to Clipboard?
opacity: .01;
does the job. You should combine it with:
height:0;
position:absolute;
z-index: -1;
Do not use pointer-events:none;
as it will stop .select()
from working, as well.
function copyContents() { $('#element_html').select(); document.execCommand('copy');}
#element_html { position: absolute; opacity: .01; height: 0; overflow: hidden;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="element_html">Which textarea?</textarea><button onclick="copyContents()">Copy</button>
<input type="text" placeholder="Paste it here...">
Copy text to clipboard from hidden input is not working in jQuery
You can try to change the type of the input to text before select then, and bring the type hidden back after like that.
$("button").on("click", function() { var n = $("#copyMe").text(); $(".copied").attr("value", n); $(".copied").attr("type", "text").select(); document.execCommand("copy") $(".copied").attr("type", "hidden")});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p id="copyMe">This is the copied text!</p><input type="hidden" class="copied"/><button>COPY</button><input type="text" placeholder="paste copied text here"/>
Copy text to clipboard now that execCommand(copy) is obsolete
From Klaycon's comment to the question. The replacement is the Clipboard API. It is not implemented in all browsers, but most.
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
// In this example, the text to copy would be in an element with id = textcopy
var text_to_copy = document.getElementById("textcopy").innerHTML;
if (!navigator.clipboard){
// use old commandExec() way
} else{
navigator.clipboard.writeText(text_to_copy).then(
function(){
alert("yeah!"); // success
})
.catch(
function() {
alert("err"); // error
});
}
For some browsers (like Firefox) this only works when initiated by a user action. So, put the code inside a button listener, for example.
I tested this (Feb 2020) in (Windows) Chrome, Firefox, new Edge, Opera, iOS Safari, iOS Chrome, iOS app webview. Clipboard writeText works great.
Make execCommand(Copy) work on hidden input tags
The execCommand works to those elements added to the any part of the document element.
the code lacks document.querySelector("body").appendChild(hiddenItem);
and can be hidden after executing the command -> hiddenItem.setAttribute("style","display: none");
Javascrypt copy to clipboard function copying just first row
first, you need remove id property ("key") from your input text, because there should be no duplicate ids on a document.
Then you can change your js, taking the input ("key") element by its sibling to current clicked button.
function myFunction(el) {
var hidden = el.previousElementSibling;
hidden.style.display = 'block';
hidden.select();
hidden.setSelectionRange(0, 99999)
document.execCommand("copy");
alert("Copied the text: " + hidden.value);
hidden.style.display = 'none';
}
<table>
<tr>
<td class="ttd"> </td>
<td class="ttd">1</td>
<td class="ttd">2</td>
<td class="ttd">3</td>
<td class="ttd">4</td>
<td class="ttd">5</td>
<td class="ttd">6</td>
<td class="ttd">7</td>
<td class="ttd">
<input type="text" style="display:none;" value="12321">
<button onclick="myFunction(this)" >Copy</button>
</td>
</tr>
<tr>
<td class="ttd"> </td>
<td class="ttd">1</td>
<td class="ttd">2</td>
<td class="ttd">3</td>
<td class="ttd">4</td>
<td class="ttd">5</td>
<td class="ttd">6</td>
<td class="ttd">7</td>
<td class="ttd">
<input type="text" style="display:none;" value="2222">
<button onclick="myFunction(this)" >Copy</button>
</td>
</tr>
</table>
Copying a text in React via creating a hidden input
This will work for you
var input = document.createElement("input");
document.body.appendChild(input);
input.value = textToCopy
input.select();
document.execCommand("copy");
document.body.removeChild(input);
OR
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = textToCopy
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
Related Topics
How to Scroll to Top of Page With JavaScript/Jquery
How to Get Browser Width Using JavaScript Code
Coordinates of Selected Text in Browser Page
Programmatically Trigger "Select File" Dialog Box
How to Escape Quotes in HTML Attribute Values
Angularjs - Ng-Disabled Not Working For Anchor Tag
How to Simulate a Mouseover in Pure JavaScript That Activates the CSS ":Hover"
Ios 8 Removed "Minimal-Ui" Viewport Property, Are There Other "Soft Fullscreen" Solutions
Get Computed Font Size For Dom Element in Js
Node.Js App Can't Run on Port 80 Even Though There's No Other Process Blocking the Port
Sorting Options Elements Alphabetically Using Jquery
Prevent Contenteditable Adding ≪Div≫ on Enter - Chrome
Benefits of Loading Js At the Bottom as Opposed to the Top of the Document
How to Detect Which One of the Defined Font Was Used in a Web Page
Get Caret Position in HTML Input
How to Get Number of Rows in ≪Textarea ≫ Using JavaScript