Reputation: 697
I want to to be able to copy a text string on click without a button. The text string will be inside a "span" class.
Upvotes: 61
Views: 158573
Reputation: 1
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"))
}
});
textevent.preventDefault()
<span>text</span>
Upvotes: 0
Reputation: 1
Most answers I have found here seem to be outdated. You should use the clipboard API instead of execCommand. This code should work:
let textString = document.querySelector('span.textstring').textContent; //Get value of the string you want to copy
const copyText = async () => {
try {
await navigator.clipboard.writeText(textString);
console.log('Content copied to clipboard!');
} catch (err) {
console.log('Copy failed!');
}
}
document.querySelector('span.textstring').addEventListener('click', copyText); //Add the event handler click, so when the span is clicked, the value is copied
Inspired and adapted by: https://www.freecodecamp.org/news/copy-text-to-clipboard-javascript/
Upvotes: 0
Reputation: 47287
The simplest modern solution is:
navigator.clipboard.writeText(value)
That value can later be accessed with:
navigator.clipboard.readText()
NOTE: This requires
https
, meaning it won't work onlocalhost
by default
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()
insteadcopy('string')
Upvotes: 32
Reputation: 81
The execCommand() method, previously used for copying text to the clipboard, has been deprecated and should not be used in modern web development. Instead, the navigator.clipboard API is now the recommended way to perform clipboard operations in the browser. This API is a built-in browser Web API, which means that it is both secure and easy to integrate into your web applications without any external dependencies.
The Clipboard API can be used to implement cut, copy, and paste features within a web application.
The following code snippets will only copy the content of the clicked span element.
jQuery:
$(document).on('click', 'span', function() {
let copyText = $(this)[0].textContent
navigator.clipboard.writeText(copyText)
})
Javascript
document.addEventListener('click', function(event) {
if (event.target.tagName === 'SPAN') {
let copyText = event.target.textContent;
navigator.clipboard.writeText(copyText);
}
});
Feel free to customize accordingly.
Upvotes: 7
Reputation: 71
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>
Upvotes: 2
Reputation: 822
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>
Upvotes: 3
Reputation: 4648
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>
Upvotes: 4
Reputation: 13257
Along with copying the text , you also have to make sure that any previously selected component remains selected after copying to clipboard.
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
Upvotes: 11
Reputation: 263
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>
Upvotes: -4
Reputation: 2459
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);
}
};
Upvotes: 3
Reputation: 22500
Try this .document.execCommand('copy')
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>
Upvotes: 46
Reputation: 1
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>
Upvotes: 71
Reputation: 15595
<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();
}
Upvotes: 22