Reputation: 4424
I want to copy
a text into clipboard
but for some reasons its not working nor it is throwing any errors
.
Below is my code.
function copy(obj)
{
var $body = document.getElementsByTagName('body')[0];
var $tempInput = document.createElement('INPUT');
$body.appendChild($tempInput);
$tempInput.setAttribute('value', '1234')
$tempInput.select();
document.execCommand('copy');
$body.removeChild($tempInput);
}
I want to copy this text on click of anchor tag having href which is causing the issue it seems. Any leads much appreciated.
Upvotes: 0
Views: 317
Reputation: 9653
obj
is not using in your function copy
function copyToClipboard() {
location.href='#popup1';
var $body = document.getElementsByTagName('body')[0];
var $tempInput = document.createElement('INPUT');
$body.appendChild($tempInput);
$tempInput.setAttribute('value', '1234')
$tempInput.select();
document.execCommand('copy');
$body.removeChild($tempInput);
alert("Text Copied");
}
<a class="coup-copybutton" href="#" onclick="copyToClipboard()">Copy</a>
Upvotes: 1
Reputation: 6902
Your function works perfectly fine, I suspect your issue is with actually calling the function on button click.
Below is the exact same code you have, except I removed the obj
parameter since it is never used. I also created a button which calls the function when clicked.
function copy()
{
var $body = document.getElementsByTagName('body')[0];
var $tempInput = document.createElement('INPUT');
$body.appendChild($tempInput);
$tempInput.setAttribute('value', '1234')
$tempInput.select();
document.execCommand('copy');
$body.removeChild($tempInput);
}
document.getElementById("copy_btn").onclick = copy;
<button id="copy_btn">Copy</button>
<input type="text" placeholder="Paste here..."/>
Upvotes: 1
Reputation: 5380
This works for me
export const copyText = (text) => {
const input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
const result = document.execCommand('copy');
document.body.removeChild(input);
return result;
};
Upvotes: 0