0

I'm trying to copy to clipboard a link ( the current link of the page ) using JS, but the console tells me that toCopy.select is not a function, why's that ? Here's the code :

HTML/PHP

<a href="javascript:void(0)" id="copy"><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/icons/link.png" alt="link">
</a>
    <textarea id="to-copy" style="display: none;"><?php echo $current_url; ?></textarea>

JS

var toCopy = document.getElementById('to-copy'),
    btnCopy = document.getElementById('copy');

btnCopy.addEventListener('click', function () {
    toCopy.select();
    document.execCommand('copy');
    return false;
});

Can anyone tell me why ? Thanks !

Mael Landrin
  • 93
  • 1
  • 10
  • Changed it, my bad, now I don't ahve an error, but it doesn't copy to clipboard ! And I've tried a lot of things, it has never worked, I've always had an error :/ – Mael Landrin Nov 06 '18 at 16:48
  • Specifically your code the problem seems to be `display: none;`, the browser can't select and copy text that it is not displaying https://jsbin.com/soquvomogu/1/edit?html,js,console,output – William Lohan Nov 06 '18 at 16:59
  • I was posting my astonishing answer but then the question is locked. Just change "display: none" to "margin-left: 100%;" so that the element actually exists – DavidC Nov 06 '18 at 17:08

1 Answers1

-1

try this

var copyBtn = document.querySelector('#button1');
copyBtn.addEventListener('click', function () {
var textarea = document.querySelector('#textarea');
textarea.select();
var text = document.execCommand('copy'); // or 'cut'
console.log(text)