Copy Text to clipboard using HTML button [duplicate] - javascript

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

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>

Copy to clipbord on jquery not worked [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>

Is there a way to select any type of text? [duplicate]

This question already has answers here:
How to copy text from a div to clipboard
(11 answers)
Closed 3 years ago.
I am trying to select a <p> element with the function .select().
I know that you can select text inside an input element, but I have not found a way to select text from other elements.
I have tried document.getElementById(), but it doesn't seem to work.
<p id='test'>Text to select.</p>
<button onclick='copy()'>Click</button>
function copy() {
var x = document.getElementById('test');
x.select();
document.execCommand('copy');
}
I then receive an error message that says 'x.select is not a function.'.
Here is the code that can help!!!!!!
<html>
<body>
<p id="foo">
some text <br />
<span>this div is child of p</span>
</p>
<button onclick="selectText('foo');">click me</button>
<script>
function selectText(element) {
var doc = document;
var text = doc.getElementById(element);
if (doc.body.createTextRange) { // ms
var range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { // moz, opera, webkit
var selection = window.getSelection();
var range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
</script>
</body>
</html>
keep me posted if you need any help...
I correctly understood that you need to get the text from the paragraph?
In this case, you can do this:
document.getElementById("test").innerText
function copy() {
var x = document.getElementById('test');
x.select();
document.execCommand('copy');
}
<input id='test' />
<button onclick='copy()'>Copy to clipboard</button>
The HTMLInputElement.select() method selects all the text in a element or in an element that includes a text field.
You can select and then copy only things that are included in text fields, your text is in a div.
By transforming that div into an input you can copy to clipboard the text that you just inputed into the text field.
See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

Copy text string on click

I spent a good 20 min searching online for this, but couldn't find it. What I want is to to be able to copy a text string on click without a button. The text string will be inside a "span" class.
User hovers over text string
User clicks text string
Text string is copied to clipboard
Any help would be greatly appreciated. Thanks!
You can attach copy event to <span> element, use document.execCommand("copy") within event handler, set event.clipboardData to span .textContent with .setData() method of event.clipboardData
const span = document.querySelector("span");
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
<span>text</span>
Try this .document.execCommand('copy')
click the element and copy the text and post with tmp input element
Then copy the text from this input
function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}
<p onclick="copy(this)">hello man</p>
This is the Code pen.
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<p style="color:wheat;font-size:55px;text-align:center;">How to copy a TEXT to Clipboard on a Button-Click</p>
<center>
<p id="p1">This is TEXT 1</p>
<p id="p2">This is TEXT 2</p><br/>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
<br/><br/><input class="textBox" type="text" id="" placeholder="Dont belive me?..TEST it here..;)" />
</center>
Jquery Code here
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
Use the Clipboard API!
The simplest modern solution is:
navigator.clipboard.writeText(value)
That value can later be accessed with:
navigator.clipboard.readText()
NOTE: To use in an iframe, you'll need to add write (and maybe read) permissions
<iframe src='' allow='clipboard-read; clipboard-write'/>
NOTE: To use in an browser extension (on a webpage), you'll need either to:
call from a user triggered event (click...)
add the 'clipboardWrite' permission to the manifest
NOTE: To use in the dev console, use copy() instead
copy('string')
W3Schools Tutorial
CanIUse
Along with copying the text , you also have to make sure that any previously selected component remains selected after copying to clipboard.
Here's the full code :
const copyToClipboard = str => {
const el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
? document.getSelection().getRangeAt(0) // Store selection if found
: false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};
ps adding the source
HTML:
<button type='button' id='btn'>Copy</button>
JS
document.querySelect('#btn').addEventListener('click', function() {
copyToClipboard('copy this text');
});
JS / Function:
function copyToClipboard(text) {
var selected = false;
var el = document.createElement('textarea');
el.value = text;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
if (document.getSelection().rangeCount > 0) {
selected = document.getSelection().getRangeAt(0)
}
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
guest271314's answer applied to multiple elements:
spans = document.querySelectorAll(".class");
for (const span of spans) {
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
}
<span class="class">text</span>
<br>
<span class="class">text2</span>
This is the most suitable way to do it. It will copy all text in elements with the class "copy" in them.
var copy = document.querySelectorAll(".copy");
for (const copied of copy) {
copied.onclick = function() {
document.execCommand("copy");
};
copied.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", copied.textContent);
console.log(event.clipboardData.getData("text"))
};
});
};
.copy {
cursor: copy;
}
<p><span class="copy">Text</span></p>
<p><span class="copy">More Text</span></p>
<p><span class="copy">Even More Text</span></p>
u can also use onclick like
function copyCode() {
const Code = document.querySelector("input");
Code.select();
document.execCommand("copy", false);
}
<input type="input" />
<button onclick={copyCode()}>Copy</button>
function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}
<p onclick="copy(this)">hello man</p>

How to execute ctrl+c or copy commad using javascript or jquery on button click

Is it possible to execute copy command using click EVENT?
I have some text selected and I want this text to be copied on onClick event, so that I am able to past this text to another page with out using right click or CTRL+C to copy the text.
function copyText(){
var txt = '';
if (window.getSelection)
txt = window.getSelection();
else if (document.getSelection)
txt = document.getSelection();
else return;
document.getElementById("a").value=txt;
allCopied =document.getElementById("a").createTextRange();
allCopied.execCommand("RemoveFormat");
allCopied.execCommand("Copy");
}
but for security reasons most browsers do not allow to modify the clipboard( except Internet explorer).
HTML
<form name="myForm">
<span onclick="copyText(this)" >Text1</span>, <span onclick="copyText(this)" >Text2</span>
<br>
<input name="myField"></input>
JavaScript
function copyText(element) {
document.myForm.myField.value = element.innerHTML;
}
Copy to Clip Board Ctrl+C
$("#text1").click(function(){
var holdtext = $("#clipboard").innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
});
use getselection() to get selected text inside a browser window

Categories

Resources