Copy to clipbord on jquery not worked [duplicate] - javascript

Here is my code for when the user clicks on this button:
<button id="button1">Click to copy</button>
How do I copy the text inside this div?
<div id="div1">Text To Copy</div>

I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work.
After trying I got to:
<html>
<body>
<div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
<script>
function copyDivToClipboard() {
var range = document.createRange();
range.selectNode(document.getElementById("a"));
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
}
</script>
</body>
</html>
Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)
Update March 27th, 2019.
For some reason document.createRange() didn't work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0).

Both examples work like a charm :)
JAVASCRIPT:
function CopyToClipboard(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
alert("Text has been copied, now paste in the text-area")
}
}
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
<br /><br />
<div id="div1">Text To Copy </div>
<br />
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
JQUERY (relies on Adobe Flash):
https://paulund.co.uk/jquery-copy-to-clipboard

The accepted answer does not work when you have multiple items to copy, and each with a separate "copy to clipboard" button. After clicking one button, the others will not work.
To make them work, I added some code to the accepted answer's function to clear text selections before doing a new one:
function CopyToClipboard(containerid) {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
}
}

I was getting selectNode() param 1 is not of type node error.
changed the code to this and its working. (for chrome)
function copy_data(containerid) {
var range = document.createRange();
range.selectNode(containerid); //changed here
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
alert("data copied");
}
<div id="select_txt">This will be copied to clipboard!</div>
<button type="button" onclick="copy_data(select_txt)">copy</button>
<br>
<hr>
<p>Try paste it here after copying</p>
<textarea></textarea>

This solution add the deselection of the text after the copy to the clipboard:
function copyDivToClipboard(elem) {
var range = document.createRange();
range.selectNode(document.getElementById(elem));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
}

<div id='myInputF2'> YES ITS DIV TEXT TO COPY </div>
<script>
function myFunctionF2() {
str = document.getElementById('myInputF2').innerHTML;
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
alert('Copied the text:' + el.value);
};
</script>
more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

Here you can see code which works on different browsers, including iOS.
const copyToClipboard = (id) => {
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand("copy");
window.getSelection().removeAllRanges();
};
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
const copyIOS = (id) => {
const text = document.getElementById(id).innerHTML;
if (!navigator.clipboard) {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.fontSize = "20px";
document.body.appendChild(textarea);
const range = document.createRange();
range.selectNodeContents(textarea);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textarea.setSelectionRange(0, 999999);
document.execCommand("copy");
document.body.removeChild(textarea);
}
navigator.clipboard.writeText(text);
};
const copyTextById = (id) => {
if (isIOS) {
return copyIOS(id);
}
copyToClipboard(id);
};
window.copyTextById = copyTextById
<div id="text">Text which you will copy</div>
<button onclick="copyTextById('text')">Click me</button>

Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.
This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.

Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".
<script>
$( document ).ready(function() {
$(".code").click(function(event){
var range = document.createRange();
range.selectNode(this);
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
});
});
</script>

Non of all these ones worked for me. But I found a duplicate of the question which the anaswer worked for me.
Here is the link
How do I copy to the clipboard in JavaScript?

The solutions above do not work for the content editable div. A few more steps are needed to copy its content to the clipboard.
Here is how to copy div contenteditable to the clipboard. Selecting text on the iphone and Android is not always easy. With one Copy button you can copy all the content.
<div id="editor1" contenteditable="true"></div>
<button id="button1" onclick="CopyToClipboard()">COPY</button>
<script>
function CopyToClipboard() {
var copyBoxElement = document.getElementById('editor1');
copyBoxElement.contenteditable = true;
copyBoxElement.focus();
document.execCommand('selectAll');
document.execCommand("copy");
copyBoxElement.contenteditable = false;
alert("Text has been copied")
}
</script>

Related

Set select for a <p> in Javascript [duplicate]

Here is my code for when the user clicks on this button:
<button id="button1">Click to copy</button>
How do I copy the text inside this div?
<div id="div1">Text To Copy</div>
I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work.
After trying I got to:
<html>
<body>
<div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
<script>
function copyDivToClipboard() {
var range = document.createRange();
range.selectNode(document.getElementById("a"));
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
}
</script>
</body>
</html>
Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)
Update March 27th, 2019.
For some reason document.createRange() didn't work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0).
Both examples work like a charm :)
JAVASCRIPT:
function CopyToClipboard(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
alert("Text has been copied, now paste in the text-area")
}
}
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
<br /><br />
<div id="div1">Text To Copy </div>
<br />
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
JQUERY (relies on Adobe Flash):
https://paulund.co.uk/jquery-copy-to-clipboard
The accepted answer does not work when you have multiple items to copy, and each with a separate "copy to clipboard" button. After clicking one button, the others will not work.
To make them work, I added some code to the accepted answer's function to clear text selections before doing a new one:
function CopyToClipboard(containerid) {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
}
}
I was getting selectNode() param 1 is not of type node error.
changed the code to this and its working. (for chrome)
function copy_data(containerid) {
var range = document.createRange();
range.selectNode(containerid); //changed here
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
alert("data copied");
}
<div id="select_txt">This will be copied to clipboard!</div>
<button type="button" onclick="copy_data(select_txt)">copy</button>
<br>
<hr>
<p>Try paste it here after copying</p>
<textarea></textarea>
This solution add the deselection of the text after the copy to the clipboard:
function copyDivToClipboard(elem) {
var range = document.createRange();
range.selectNode(document.getElementById(elem));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
}
<div id='myInputF2'> YES ITS DIV TEXT TO COPY </div>
<script>
function myFunctionF2() {
str = document.getElementById('myInputF2').innerHTML;
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
alert('Copied the text:' + el.value);
};
</script>
more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
Here you can see code which works on different browsers, including iOS.
const copyToClipboard = (id) => {
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand("copy");
window.getSelection().removeAllRanges();
};
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
const copyIOS = (id) => {
const text = document.getElementById(id).innerHTML;
if (!navigator.clipboard) {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.fontSize = "20px";
document.body.appendChild(textarea);
const range = document.createRange();
range.selectNodeContents(textarea);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textarea.setSelectionRange(0, 999999);
document.execCommand("copy");
document.body.removeChild(textarea);
}
navigator.clipboard.writeText(text);
};
const copyTextById = (id) => {
if (isIOS) {
return copyIOS(id);
}
copyToClipboard(id);
};
window.copyTextById = copyTextById
<div id="text">Text which you will copy</div>
<button onclick="copyTextById('text')">Click me</button>
Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.
This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.
Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".
<script>
$( document ).ready(function() {
$(".code").click(function(event){
var range = document.createRange();
range.selectNode(this);
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
});
});
</script>
Non of all these ones worked for me. But I found a duplicate of the question which the anaswer worked for me.
Here is the link
How do I copy to the clipboard in JavaScript?
The solutions above do not work for the content editable div. A few more steps are needed to copy its content to the clipboard.
Here is how to copy div contenteditable to the clipboard. Selecting text on the iphone and Android is not always easy. With one Copy button you can copy all the content.
<div id="editor1" contenteditable="true"></div>
<button id="button1" onclick="CopyToClipboard()">COPY</button>
<script>
function CopyToClipboard() {
var copyBoxElement = document.getElementById('editor1');
copyBoxElement.contenteditable = true;
copyBoxElement.focus();
document.execCommand('selectAll');
document.execCommand("copy");
copyBoxElement.contenteditable = false;
alert("Text has been copied")
}
</script>

Place small "Copied" confirmation in the div that is copied by click

I have a wordpress site with a DIV that I copy its content via a link using a simple javascript code. I need a message to replace the copied content saying "Copied" in the div AFTER its copied.
Very challenging. Need help to do this.
<div class="btcTXT" id="btc">bc1q978cape6n3sez2ahp59s7jr59j70nqq2x3tt8c</div>
<div onclick="CopyToClipboard('btc');return false;" class="cpy"><i class="far fa-copy"></i> </div>
<script>
function CopyToClipboard(id)
{
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
</script>
You're almost there...
function CopyToClipboard(id) {
let item = document.getElementById(id);
var r = document.createRange();
r.selectNode(item);
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
item.innerText = 'Copied';
}

Copy Text to clipboard using HTML button [duplicate]

This question already has answers here:
How do I copy to the clipboard in JavaScript?
(27 answers)
Closed 2 years ago.
How do I actually copy some fixed text to clipboard using javascript?
This is my code and it's not working maybe there's another way and I don't know.
<button onclick="Copy()">Copy</button>
<script>
function Copy() {
document.execCommand("copy","Some text here");
}
</script>
I want to copy some fixed text using just button, so I don't have to select texts manually and copy them.
Thanks.
You can try this approach:
<script>
function Copy() {
var copyText = document.createElement("input");
copyText.style="display:none";
copyText.value = "This is a paragraph";
document.body.appendChild(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
try it:
var copy_text_val = document.querySelector('.copy_text');
function Copy() {
copy_text_val.select();
document.execCommand("copy");
console.log(copy_text_val.value);
}
<button onclick="Copy()">Copy</button>
<input type="text" class="copy_text" value="blablabla">
For this action you have to select the text dynamically before actually copying it:
Here is an example:
function copy_text(node){
if(document.body.createTextRange){
const range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
document.execCommand('copy');
}
else if(window.getSelection){
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
}
else {
console.warn("Could not select text in node");
}
}
// This copy_text function ensures cross-browser compatibility
// What it does is select the text within the range of the node holding the text
// Then executes the "copy" command on that selected text
function clear_selection(){
if(window.getSelection){
window.getSelection().removeAllRanges();
}
else if(document.selection){
document.selection.empty();
}
}
// This clear_selection function clears any selection from the document
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("clipboard-exec").onclick = function(){
copy_text(document.getElementById("clipboard-text"));
// Copy the text on clicking the button
setTimeout(() => { clear_selection() }, 500);
// Clear the selection after 0.5s
}
});
<span id="clipboard-text">This is the text that will be copied to your clipboard when you click on the "Copy" button.</span>
<button><span id="clipboard-exec"><i class="fa fa-copy"> Copy</i></span></button>
Of course with this function you can just restructure it to fit your needs.
Also note that what you are trying to accomplish by copying directly to the keyboard without a valid text node actually holding the text won't work, I guess for security purposes
But you can create a node in the document with the text but hide it from view then select it using this function .. NOTE the text you are copying to the clipboard has to be actually in the document, for you to execute the "copy" command on it

How to copy the code shown in my webpage with a button embedded in it

function copy() {
var x= document.getElementById("content");
x.select();
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
this is the js code that i used to select and copy the content of input.
what to do if i want to add a button on my webpage to select some div and copy the shown code in clipboard.
Try just using the dummy input method:
function copy() {
const text = document.getElementById("copyDiv").innerText;
const elem = document.createElement("input");
document.body.appendChild(elem);
elem.value = text;
elem.select();
document.execCommand("copy");
document.body.removeChild(elem);
document.write("Copied to clipboard!");
}
<div id="copyDiv">Text to be copied</div>
<button onclick="copy()">Copy text</button>
here i figured out the solution of my own problem.
Html:
<div id="divid" onclick="copy('divid')">Division to be copied</div>
js:
function copy(i)
{
var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
}

The opposite to window.getSelection()

I am selecting a text to copy it by using window.getSelection().addRange(range):
var targetelement = document.getElementById("someid"),
range = document.createRange();
range.selectNode(targetelement);
window.getSelection().addRange(range);
document.execCommand('copy')
It works, but the browser(firefox) selects the text inside the tag after the completion of the code. How can I diselect it? Is there some kind of opposite to window.getSelection function or method?
After copy trigger a focus or blur to this input field to diselect the text.
<div id="someid">
This is a test man
</div>
<div id="empty">
</div>
<script>
var targetelement = document.getElementById("someid");
var range = document.createRange();
range.selectNode(targetelement);
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
</script>
https://jsfiddle.net/s1teLukn/5/
This old code works in all browsers:
var sel = window.getSelection ? window.getSelection() : document.selection;
if (sel) {
if (sel.removeAllRanges) {
sel.removeAllRanges();
} else if (sel.empty) {
sel.empty();
}
}

Categories

Resources