How to save string in clipboard using pure javascript? - javascript

I want to make a bookmarklet to save a string parsed from an Array and I'm looking for an easy way to save my const cp = 'text' into clipboard. Is there any solution for this problem? Thanks in advance :)

Have a look around before posting. This is from the w3schools site. Lots of great explanations there. https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}

I have used the following function to achieve this.
const copyToClipboard = (e) => {
const el = document.createElement('input')
el.value = window.location // I need a string that was located in the url => you should use whatever value you need, and set the input value to that, obviously.
el.id = 'url'
el.style.position = 'fixed'
el.style.left = '-1000px' // otherwise, sometimes, it creates an input element visible on the screen
el.setAttribute('readonly', true) // to prevent mobile keyboard from popping up
document.body.appendChild(el)
el.select()
document.execCommand('copy')
}

You can create a function like this using copy event
const copyToClipboard = (text) => {
document.addEventListener('copy', function(e) {
e.clipboardData.setData('text/plain', text);
e.preventDefault();
});
document.execCommand('copy');
}
This answer is also helpful.

Related

How to copy custom texts into clipboard when click on a button?

I have an input, and would like to make have a copy link next to its label.
When I click copy I want to not only copy the input value, but I would like to prepend more texts.
http://www.test.com?code= + input value
How do I do that?
//copy text
function getLink(id) {
var copyText = document.getElementById(id);
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
With this code above, only copy the value.
You can edit the value in the current input element, and then restore it to the original value after copied the edited value. Something like this:
function getLink(e) {
const copyPad = e.target.previousElementSibling,
storedValue = copyPad.value,
copyValue = 'http://www.test.com?code=' + storedValue;
copyPad.value = copyValue;
copyPad.select();
copyPad.setSelectionRange(0, 99999); /* For mobile devices */
document.execCommand("copy");
console.log("Copied the text: " + copyPad.value);
copyPad.value = storedValue;
}
const but = document.querySelector('#copyLink');
but.addEventListener('click', getLink);
<input><button id="copyLink">Copy</button>
<input> Paste here to check
A user can't see changes to the input element, because the page is not rendered before all the JS has been executed.

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 a calculated value to clipboard?

I've got a formula that calculates a value. This value I want to insert to an Excel sheet. To make it comfortable to the user I want to put it to the clipboard automatically.
I try to do my first steps in JS and encountered this (probably) very simple problem. But all methods I found are related to raw values of html input-tags. I never have seen any copy-to-clipboard functions from values created in js.
var EEFactor = 1*1; // just a formula to calculate a value
copyValue2Clipboard(EEFactor);
function value2Clipboard(value) {
// please help
}
There is an example with a great explanation here
Try like this.
function copyToClipboard(str) {
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
};
var EEFactor = 1*1;
copyToClipboard(EEFactor);
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
}
};

How to select() elements background color?

I am trying to write function that will select elements color on click and copy it to clipboard.
My function looks like this:
$(".color").click( function () {
color = getComputedStyle(this).backgroundColor;
color.select();
document.execCommand("copy");
})
Console shows error
Uncaught TypeError: color.select is not a function.
Do you know any other way to get this working?
if i understand well, you want to copy background color property to clipboard.
i got help from this link.
https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
And i tried in jsfiddle, it works fine. I hope this help
<div class="color">hello</div>
>
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
$('.color').click( function () {
color = $(this).css( "background-color" );
copyToClipboard(color);
});

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>

Categories

Resources