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
Ok so feels like i have gone down a rabbit hole of how to copy text to clipboard on here and tried a lot of suggestions
seems easy to do it for chrome but that option doesn't work in other browsers
I have a few requirements
I would like to copy text to clipboard
to be able to copy a section of html with multiple elements
To work in safari and chrome at least
Vanilla Javascript
I have found this solution and it works except that it copies the html tags as well?
i tried changing the .innerHTML to .value on the button, but that comes back undefined
<div id="something">
<div>first name: <span class="name">name</span></div>
<div>Job title: <span class="job">job</span></div>
<div>Phone number: 0123456789</div>
<img class="companylogo" src="./img/example.jpg">
</div>
<button onclick="copyToClipboard(document.getElementById('something').innerHTML)">
Copy the stuff
</button>
<script>
/* copy function */
function copyToClipboard(textToCopy) {
var textArea;
function isOS() {
//can use a better detection logic here
return navigator.userAgent.match(/ipad|iphone/i);
}
function createTextArea(text) {
textArea = document.createElement('textArea');
textArea.readOnly = true;
textArea.contentEditable = true;
textArea.value = text;
document.body.appendChild(textArea);
}
function selectText() {
var range, selection;
if (isOS()) {
range = document.createRange();
range.selectNodeContents(textArea);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
}
function copyTo() {
document.execCommand('copy');
document.body.removeChild(textArea);
}
createTextArea(textToCopy);
selectText();
copyTo();
}
</script>
document.getElementById('something').innerHTML
sends html code inside #something to copyToClipboard and this behavior you mentiond is expected . what do you want to be copied to clipboard if not html ?
thanks Hosseind600 for trying to help
but i managed to find some code that does exactly what i would like it to do. whilst ticking off the requirements i had set
its currently the second answer but highest votes
How to copy text from a div to clipboard
<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>
Can anyone help to crack out this Javascript?
const copyButton = document.querySelector('.copyButton');
const copyalert = document.querySelector('.copyalert');
copyButton.addEventListener('click', copyClipboard);
function copyClipboard() {
var copystatus= document.getElementById("randomstatus");
// for Internet Explorer
if(document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(copystatus);
range.select();
document.execCommand("Copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
else if(window.getSelection) {
// other browsers
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(copystatus);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
}
This javascript is used to copy the text inside a <p> element.
My Html Code
<p id="randomstatus">Strangers think I'm Quiet. My Friends think I'm outgoing. My best friends know that I'm Completely Insane</p>
<button class="copyButton btn" id="copyButton"><i class="fas fa-clipboard"></i> Copy</button>
<span class="copyalert">Copied!</span>
This works perfectly for one but I need the copy buttons to place more times in my web page. But I have stucked here. Please help me.
A basic approach is to add an onclick event attribute to each of your buttons that will be used to call your copyClipboard() function
<button class="copyButton btn" id="copyButton" onclick = 'copyClipboard()'><i class="fas fa-clipboard"></i> Copy</button>
<button class="copyButton btn" id="copyButton1" onclick = 'copyClipboard()'><i class="fas fa-clipboard"></i> Copy</button>
and change your JavaScript script to this
function copyClipboard() {
var copyalert = document.querySelector('.copyalert');
var copystatus= document.getElementById("randomstatus");
// for Internet Explorer
if(document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(copystatus);
range.select();
document.execCommand("Copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
else if(window.getSelection) {
// other browsers
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(copystatus);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
}
I have a JS function that copies a Div to the clipboard to be pasted into Outlook as an email, however on IE and Edge Chromium it's showing elements that are hidden with style="display:none" that shouldn't be shown in emails. Is this a limitation of Chromium/IE, as this was previously working fine in Edge Legacy?
function copyEmail(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
document.execCommand("Copy");
}
<input type="button" value="Copy Email Content" onclick="copyEmail(document.getElementById('emailcontentcopy'))">
<div id="emailcontentcopy">
<table style="display:none">
<tr><td>content not to display</td></tr>
</table>
<table style="display:block">
<tr><td>content to be shown</td></tr>
</table>
</div>
Emails are tricky and come with an all new set of expected behaviours and respective bug fixes.
The best solution would be to remove the table you don't want to be shown, instead of just hiding it.
If you can't remove it, try adding the Outlook attribute mso-hide:all to the hidden tables. For other mail servers try display:none !important.
I tried...
const selBox = document.createElement('textarea');
const selBox1 = (selBox);
selBox1.style.position = 'fixed';
selBox1.style.left = '0';
selBox1.style.top = '0';
selBox1.style.opacity = '0';
selBox1.value = val;
document.body.appendChild(selBox);
selBox1.focus();
selBox1.select();
document.execCommand('copy');
document.body.removeChild(selBox)
But it only copy the inner text value only.
And I want to full div with same CSS property. For pasting it on the mail or another place.
CopyFunction=()=> {
const elm = document.getElementById("copyCodeId");
// for Internet Explorer
if (document.body.createTextRange) {
const range = document.body.createTextRange();
range.moveToElementText(elm);
range.select();
document.execCommand("copy");
alert("Copied div content to clipboard");
} else if (window.getSelection) {
// other browsers
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(elm);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
alert("Copied div content to clipboard");
}
}
<div class="code-bg" id="copyCodeId">
Click on the button to copy the text from the div element. Try to paste the text<span style="color:red"> (e.g. ctrl+v)</span> afterwards in a different window, to see the effect.
</div>
<button onclick="CopyFunction()">Copy div</button>
I found the following code online which works well. I would like to use this on multiple elements on the same page and do not know how to do this. I can get the first to work but not the second.
Can anyone help?
Thanks,
John
Javascript:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
document.onclick = function(e) {
if (e.target.className === 'select') {
SelectText('some_text');
}
};
HTML:
<span id ='some_text'>Text to select </span><span class='select'>select</span>
<span id ='more_text'>More text to select</span><span class='select'>select</span>
Because you call function with same parameter.
SelectText('some_text');
"Text to select" will be selected no matter what class="select" you click.
Try this code:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
document.onclick = function(e) {
if (e.target.className === 'select') {
SelectText(e.target.getAttribute('data-id'));
}
};
And change the HTML:
<span id ='some_text'>Text to select </span><span class='select' data-id="some_text">select</span>
<span id ='more_text'>More text to select</span><span class='select' data-id="more_text">select</span>
You can give a special attribute to each span with the id of the element you want to select:
//JS
SelectText(e.target.attributes["select"].value);
//HTML
<span class='select' select="some_text">select</span>
<span class='select' select="more_text">select</span>
Or, if the order of the elements is always similar and is not likely to change, you can retrieve the previous sibling:
SelectText(e.target.previousSibling.id);
For your case you can do:
SelectText(e.target.previousSibling.id);