Copy text string on click - javascript

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>

Related

Multiple copy to clipboard buttons - copy text from the button itself

I'm trying to build something similar to a virtual keyboard for french special characters, so the user can copy them easy by clicking on the special character button and paste them wherever they need.
I'm not very good in javascript and have been struggling with bits of code I found to create what I need. So far, I can make it work for just one button with this code.
For my html (just an excerpt)
<div class="copy_btn_container">
<div class="copy_btn_block">
<p>Accents graves et accents aigüs<p>
<button onclick="copyStringToClipboard()" id = 'accbtn1' data-target="accbtn1" class="copy_btn">é</button>
<button onclick="copyStringToClipboard()" id = 'accbtn2' data-target="accbtn2" class="copy_btn">è</button>
<button onclick="copyStringToClipboard()" id = 'accbtn3' data-target="accbtn3" class="copy_btn">à</button>
<button onclick="copyStringToClipboard()" id = 'accbtn4' data-target="accbtn4" class="copy_btn">ù</button>
</div>
</div>
And my javascript is
function copyStringToClipboard () {
var str = document.getElementById("accbtn1").innerText;
// Create new element
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);
}
So I know that document.getElementById accepts only one element, so I tried document.getElementsByClassName but it return a "undefined" value.
I'm open to other ways for the js too, as I saw that it was possible to use constants or such, but all of the example are designed to copy values from input fields, and for some reason I can't manage dont tweak them into working for copying the button's text.
Any help would be appreciated ! Thanks
You could pass the id or data attribute into your function like so:
function copyStringToClipboard (target) {
var str = document.getElementById(target).innerText;
// Create new element
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);
}
<div class="copy_btn_container">
<div class="copy_btn_block">
<p>Accents graves et accents aigüs<p>
<button onclick="copyStringToClipboard(this.getAttribute('data-target'))" id = 'accbtn1' data-target="accbtn1" class="copy_btn">é</button>
<button onclick="copyStringToClipboard(this.getAttribute('data-target'))" id = 'accbtn2' data-target="accbtn2" class="copy_btn">è</button>
<button onclick="copyStringToClipboard(this.getAttribute('data-target'))" id = 'accbtn3' data-target="accbtn3" class="copy_btn">à</button>
<button onclick="copyStringToClipboard(this.getAttribute('data-target'))" id = 'accbtn4' data-target="accbtn4" class="copy_btn">ù</button>
</div>
</div>

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');
}

Jquery HTML Copy to clipboard

In my code, I am trying to copy iframe code using copy to clipboard button but I am not satisfied with it because when I copy using button it copies < and > instead of < and > secondly it won't highlights the text area so is there any alternate solution to copy as HTML code thanks
Here is my JSfiddle
Here is a sample copied text
<iframe src='http://localhost/secvideo/cms/watch?v=30Rt9r' frameborder='0' style='overflow: hidden; position: absolute;' height='100%' width='100%'></iframe>
and Here is my JS
function copyToClipboard(elementId) {
var aux = document.createElement("input");
// Assign it the value of the specified element
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);
alert("Copied!");
}
I think you are creating an element unnecessarily here. You already have a text area with the iframe content.
All you need is to select the text area and do a document.execCommand("copy");
Modify your script to
window.copyToClipboard = function(elementId) {
// Create a "hidden" input
var aux = document.getElementById(elementId);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
alert("Copied!");
}
jsfiddle
https://jsfiddle.net/yhpe990k/1/
var copyToClipboard = function (text) {
var $txt = $('<textarea />');
$txt.val(text)
.css({ width: "1px", height: "1px" })
.appendTo('body');
$txt.select();
if (document.execCommand('copy')) {
$txt.remove();
}
};

JS - focus to a b tag

I want to set the focus to a b tag (<b>[focus should be here]</b>).
My expected result was that the b tag into the div has the focus and if I would write, that the characters are bold.
Is this impossible? How can I do this?
Idea was from here:
focus an element created on the fly
HTML:
<div id="editor" class="editor" contentEditable="true">Hallo</div>
JS onDomready:
var input = document.createElement("b"); //create it
document.getElementById('editor').appendChild(input); //append it
input.focus(); //focus it
My Solution thanks to A1rPun:
add: 'input.tabIndex = 1;' and listen for the follow keys.
HTML:
<h1>You can start typing</h1>
<div id="editor" class="editor" contentEditable="true">Hallo</div>
JS
window.onload = function() {
var input = document.createElement("b"); //create it
document.getElementById('editor').appendChild(input); //append it
input.tabIndex = 1;
input.focus();
var addKeyEvent = function(e) {
//console.log('add Key');
var key = e.which || e.keyCode;
this.innerHTML += String.fromCharCode(key);
};
var addLeaveEvent = function(e) {
//console.log('blur');
// remove the 'addKeyEvent' handler
e.target.removeEventListener('keydown', addKeyEvent);
// remove this handler
e.target.removeEventListener(e.type, arguments.callee);
};
input.addEventListener('keypress', addKeyEvent);
input.addEventListener('blur', addLeaveEvent);
};
You can add a tabIndex property to allow the element to be focused.
input.tabIndex = 1;
input.focus();//now you can set the focus
jsfiddle
Edit:
I think the best way to solve your problem is to style an input tag with font-weight: bold.
I had to cheat a little by adding an empty space inside the bold area because I couldn't get it to work on the empty element.
This works by moving the selector inside the last element in the contentEditable since the bold element is the last one added.
It can be edited to work on putting the focus on any element.
http://jsfiddle.net/dnzajx21/3/
function appendB(){
var bold = document.createElement("b");
bold.innerHTML = " ";
//create it
document.getElementById('editor').appendChild(bold); //append it
setFocus();
}
function setFocus() {
var el = document.getElementById("editor");
var range = document.createRange();
var sel = window.getSelection();
range.setStartAfter(el.lastChild);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}
The SetFocus function I took was from this question: How to set caret(cursor) position in contenteditable element (div)?

Categories

Resources