Copy to clipboard a static text? - javascript

I need to create a script that copy to clipboard's users (from any devices/OS/browser) a specific text.
I've found this library for JS ZeroClipboard. But I'am not so good in javascript, so my question is how to use this library in my script that is more or less like this.
<p id="text">text to copy</p>
<button onclick="CopyToClipboard()">Copy</button>
<script>
function CopyToClipboard(){
What i put here?
};
</script>
Help for using zeroclipboard or any other simpler way to do this?
It would be nice if it can work for most devices as possible! Thanks a lot!!!

I added comment to explain what's happening.
function CopyToClipboard() {
// Get the desired text to copy
var selectText = document.getElementById('text').innerHTML;
// Create an input
var input = document.createElement('input');
// Set it's value to the text to copy, the input type doesn't matter
input.value = selectText;
// add it to the document
document.body.appendChild(input);
// call select(); on input which performs a user like selection
input.select();
// execute the copy command, this is why we add the input to the document
document.execCommand("copy");
// remove the input from the document
document.body.removeChild(input);
}
<p id="text">text to copy</p>
<button onclick="CopyToClipboard()">Copy</button>

I think this is what you are looking for. No need to use a plugin for something as simple as you want. There is a method that lets you copy text 'execCommand("copy");'.
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
<input type="text" value="This text is still being copied" style="display:none;" id="myInput">
<button onclick="myFunction()">Copy text</button>

If you want to copy static text from the p tag or div tag use below code..
var selectText = document.getElementById('text');
var range = document.createRange();
range.selectNode(selectText);
window.getSelection().addRange(range);
document.execCommand('Copy');
window.getSelection().removeAllRanges();
which means here you create the range for your text and select the node.
After that get the selection from that range.
Finally exec the command Copy and clear the ranges.
If you want to copy the text from input box use below..
var selectText = document.getElementById('text');
selectText.select();
document.execCommand("copy");

Related

Conditional to avoid copying text inside a textarea doesn't work

I am working in a code that add some informations to a copied item in the clipboard. And besides, I'm also working to avoid that this function don't work when the selected text be inside a textarea, but without success until now.
Take a look at the source. When I run it, the extra informations are added even when the text inside the textarea is selected and copied. The intention is that extra info don't be added to the copied text inside the clipboard when the selected text be inside a textarea.
Is there anything wrong in my code?
Important: it doesn't work in Mozilla Firefox.
function addLink() {
/* The intention is that extra info don't be added to the copied text when the selected text be inside a textarea */
if (window.getSelection().baseNode.parentNode.tagName === 'TEXTAREA') return;
var selection = window.getSelection();
pagelink = "<br/></br/>Full text: " + document.title + "<br/>" + document.location.href;
copytext = ("“"+selection+"”") + pagelink;
newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function (){document.body.removeChild(newdiv);}, 100);
}
document.addEventListener('copy', addLink);
<b>It'll be added some extra info to whatever text copied inside this MRE, but the intention is that they don't be added when the selected text be inside a textarea.</b>
<p>When this text is copied, some informations are added to the clipboard.</p>
<p>Here too, but... </p>
<p><textarea id="urlCopied" rows="3" cols="30">how to avoid that extra informations be added when the copied text come from a textarea?</textarea></p>
<textarea placeholder="Paste for testing..." cols="40" rows="7"></textarea>

How to copy String into Clipboard using a onClick Eventlistener

my Question is not a duplicate, I'm not using Jquery, I'm not using a textarea. I want to copy the value of a variable into the Clipboard using vanilla javascript.
I'd like to copy a String of Text that is stored in a variable into the Clipboard using the onClick Eventlistener off a Button.
I tried modifiyng this example, which uses a input field, but it's not working. I'm only beginning to understand Javascript, so please be kind. Also I'm looking for a solution that doesn't use a library.
function myFunction() {
var copyText = "This is a Test"
copyText.select();
document.execCommand("copy");
}
<button onclick="myFunction()">Copy text</button>
You can try something like this.
function myFunction() {
// variable content to be copied
var copyText = "Test"
// create an input element
let input = document.createElement('input');
// setting it's type to be text
input.setAttribute('type', 'text');
// setting the input value to equal to the text we are copying
input.value = copyText;
// appending it to the document
document.body.appendChild(input);
// calling the select, to select the text displayed
// if it's not in the document we won't be able to
input.select();
// calling the copy command
document.execCommand("copy");
// removing the input from the document
document.body.removeChild(input)
}
<button onclick="myFunction()">Copy text</button>
The HTMLInputElement.select() method selects all the text in a element or an element with a text field.
read more here.

Copy text from <span> to clipboard

I've been trying to copy the innerContent of a <span> to my clipboard without success:
HTML
<span id="pwd_spn" class="password-span"></span>
JavaScript
Function Call
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('copy').addEventListener('click', copy_password);
});
Function
function copy_password() {
var copyText = document.getElementById("pwd_spn").select();
document.execCommand("Copy");
}
I've also tried:
function copy_password() {
var copyText = document.getElementById("pwd_spn").textContent;
copyText.select();
document.execCommand("Copy");
}
It seems like .select() doesn't work on a <span> element since I get the following error on both:
You could do this: create a temporary text area and append it to the page, then add the content of the span element to the text area, copy the value from the text area and remove the text area.
Because of some security restrictions you can only execute the Copy command if the user interacted with the page, so you have to add a button and copy the text after the user clicks on the button.
document.getElementById("cp_btn").addEventListener("click", copy_password);
function copy_password() {
var copyText = document.getElementById("pwd_spn");
var textArea = document.createElement("textarea");
textArea.value = copyText.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
}
<span id="pwd_spn" class="password-span">Test</span>
<button id="cp_btn">Copy</button>
See https://stackoverflow.com/a/48020189/2240670 there is a snippet of code for that gives you an example for a div, that also applies to a span, I did not copy it here to avoid duplication.
Basically, when you are copying to clipboard you need to create a selection of text, <textarea> and <input> elements make this easy because they have a select() method, but if you are trying to copy contents from any other type of element like a <div> or <span>, you'll need to:
Create/get a Range object(some browsers do not provide a constructor, or a decent way to do this). Calling document.getSelection().getRangeAt(0), I found works on most browsers except edge(ie11 works though).
Add the element you want to copy from to that range's selection.
Add that range to the window or document Selection.
Call document.execCommand("copy") to copy the selected text.
I also recommend checking the API of Selection and Range, that will give you a better grasp of this.
simple method
1)create a input
2)give style z-index -1 and it will be hide
var code = $("#copy-to-clipboard-input");
var btnCopy = $("#btn-copy");
btnCopy.on("click", function () {
code.select();
document.execCommand("copy");
});
<input type="input" style="width:10px; position:absolute; z-index: -100 !important;" value="hello" id="copy-to-clipboard-input">
<button class="btn btn-success" id="btn-copy">Copy</button>

Copy, paste and cut operations on Textarea

Hi All,
I'm trying put some features to textarea like copy, cut and paste buttons but even I tried many times I couldn't get only part of text inside of textarea. it comes all content.
My Code below:
function copy() {
var VAL = $("#selection").select();
var DTA = $(this).text();
document.execCommand("copy");
document.execCommand("delete");
}
My Work below:
https://jsfiddle.net/dcn7pgkn/
How it would be possible that one user may copy, paste and cut operations inside of textarea?
Thanks
First You have to add brackets to your function in HTML code
<button onclick="copy()">Copy selected text</button>
Second You have to configure your jsfiddle right, you have to specify that you are using JQuery and Load Type should be No wrap - in <head>
Your code is currently copying textarea text and clearing the textarea, for copying I don't see that this line is needed:
var DTA = $(this).text();
copying shouldn't clear textarea, this line appropriate for cut action.

How to copy markup - not just plain text - to the clipboard using legacy free JavaScript

The complete content of a <div>
<div id="myElement">
Mary had a little <b>lamb</b>, its <i>fleece</i> was white as snow. Everywhere that mary went, the lamb was sure to go.
</div>
should be copied to the clipboard using this code
const copyAll = document.querySelector("myElement");
window.getSelection().selectAllChildren(copyAll);
document.execCommand("Copy");
window.getSelection().removeAllRanges();
(For the execCommand to work, the call must be executed via an event listener)
But only the text-content is copied. Is it possible to copy the markup-code (the <i> and <b> tags) without relying on the legacy firefox clipboard add-on, too?
I used to solve this problem using a fake textarea element copying my custom text into the clipboard.
Something like this should help:
const copyText = document.querySelector("myElement").innerHTML;
copyToClipboard(copyText);
function copyToClipboard(message) {
let textArea = document.createElement("textarea");
textArea.value = message;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
document.body.removeChild(textArea);
}

Categories

Resources