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);
});
Related
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.
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
}
};
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>
I'm following a Javascript tutorial using a book.
The exercise is change the background color in a <input type="search"> using document.querySelector. When I try to search something with no text in the search box, the background from <input> changes to red. I did it using onsubmit and some conditional. But in the next part, it must returns to white bckground using onfocus and I'm not getting.
The code that I tried is
document.querySelector('#form-busca').onsubmit = function() {
if (document.querySelector('#q').value == '') {
document.querySelector('#q').style.background = 'red';
return false;
}
}
document.querySelector('#form-busca').onfocus = function() {
document.querySelector('#q').style.background = 'white';
}
Can someone help me? Thanks a lot!
almost got it dude.
change:
document.querySelector('#form-busca').onfocus
to:
document.querySelector('#q').onfocus
revised code:
correct sample:
document.querySelector('#form-busca').onsubmit = function() {
if (document.querySelector('#q').value == '') {
document.querySelector('#q').style.background = 'red';
return false;
}
}
document.querySelector('#q').onfocus = function() {
document.querySelector('#q').style.background = 'white';
}
It sounds like you want the input's background color to change to white when the input element is focused.
Try changing your onfocus selector to:
document.querySelector('#q').onfocus ...
You want the onfocus handler to be on the #q element, not on #form-busca; the form's focus doesn't matter, you want to clear the background when the input element gains focus:
document.querySelector('#q').onfocus = function() { ... }
Try the following code:
// select
var h1 = document.querySelector("h1");
// manipulate
h1.style.color = "red";
This will make the color of h1 red.
I have the following JS code for ZeroClipBoard :
onComplete: function(item) {
var text= $(item).html();//Not working when I hover the clip
//var text= 'Hello';// This is working when I hover the clip
var clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
clip.addEventListener('complete', function(client, text) {
debugstr("Copied text to clipboard: " + text );
});
clip.addEventListener('mouseOver', function(client) {
clip.setText(text);
})
// glue specifying our button AND its container
clip.glue('id_clip_button', 'id_clip_container');
},
Above oncomplete is oneofmy function which is called on some action . I get item from it which is html element.
Now in the above code :
var text= $(item).html();//Not working when I hover the clip
//var text= 'Hello';// This is working when I hover the clip
If I comment the first line and uncomment the second line the clip is working and text is getting copied to clipboard . But I have to use the value of that html element while copying the text . So how should I go with this ? I am getting the value of control at this point
var text= $(item).html();//
But when the hover function is called it is lost. I was thinking that it will be preserved via Closure. Am I missing something ? I am not able to get the value of text at this line :
clip.setText(text);
I am not able to access any variable from outside when I am inside clip.addEventListener('mouseOver', function(client) { clip.setText(text); })
The value won't be preserved in the function call, you need to use a $.proxy instead:
clip.addEventListener('mouseOver', $.proxy(function(client) {
// "this" is now set to text
clip.setText(this);
}, text));