0

I am trying to make a single button which copies text to the clipboard, but I am am having trouble. It is copying the wrong thing.

Essentially, I have a variable called my_fav_food. Then I have a button called My Fav Food. When I click this button, it calls the function copying_function and parses in the my_fav_food variable into the function. Then the function automatically copies the text to the clipboard.

<!DOCTYPE html>
<html>
<body>
<script>
var my_fav_food = "My fav food is pizza"
</script>

<button onclick="copying_function(my_fav_food)">My Fav Food</button>

<script>
function copying_function(string) {
  string.select();
  document.execCommand("string");
}
</script>

</body>
</html>
Jackie
  • 392
  • 1
  • 13
  • 2
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Andy Theos Oct 10 '18 at 12:25

2 Answers2

1

You need to create a DOM element and set the string to it then do the selection programmically. As you're not appending the element to the DOM, it will not be visible in the view.

<!DOCTYPE html>
<html>
<body>
<script>
var my_fav_food = "My fav food is pizza";
</script>

<button onclick="copying_function(my_fav_food)">My Fav Food</button>

<script>
function copying_function(string) {
 // string.select();
  const el = document.createElement('textarea');
  el.value = string;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  console.log("The data copied successfully! press `ctrl+v` to see output");
    document.body.removeChild(el);
}
</script>

</body>
</html>
Sumesh TG
  • 2,367
  • 1
  • 12
  • 29
  • Hm, doesn't seem to work. Also why are u making `el` const? – Jackie Oct 10 '18 at 12:14
  • No need to show that element in `DOM`. How can you say it not working. Did you checked? – Sumesh TG Oct 10 '18 at 12:15
  • @Ms.Tamil it just doesn't seem to copy anything. – Jackie Oct 10 '18 at 12:17
  • @Ms.Tamil Yes. I clicked the button and then I tried to paste, but all it did was paste what I had previously in my clipboard – Jackie Oct 10 '18 at 12:21
  • 1
    @Jackie The code is available in [hackernoon](https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f) site. After refer to that, it looks like you have to add the element to dom for the code to work. Sorry for the previous answer – Ms.Tamil Oct 10 '18 at 12:23
  • @Jackie Sorry, the programmically created element should add to DOM inorder work. after copy process need to remove. Now this snippet working. – Sumesh TG Oct 10 '18 at 12:26
0

The select() method can only be used to select the contents of a text field. You cannot use it the way you are using it now.

You could try: https://clipboardjs.com/

Or you might try a hack to put the text in a hidden text area (I don't guarantee this would work)

Constantin Chirila
  • 1,288
  • 1
  • 12
  • 29