0

I use the floowing javascript to copy the text from all (multiple) code elements on a webpage:

<p id="p1">Copy all code</p>

<button onclick="copyToClipboard('code')">Copy TEXT 1</button>

<script>
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
</script>

This is useful because if there are many code snippets on the page, and you want all of them, you do not have to copy them one by one. However it would be nice to separate the code copied with a blank line.

For example if I have:

<code>This is code snippet 1
</code>

<code>This is code snippet 2
</code>

The following will be copied to the clipboard:

This is code snippet 1This is code snippet 2

What I need is a line shift between the code like this:

This is code snippet 1
This is code snippet 2

As you probably guessed I want to do this without altering the content of the code snippets.

Arete
  • 948
  • 3
  • 21
  • 48
  • Did you try to set a `br` tag between the two `code` ? Perhaps this could help : https://stackoverflow.com/questions/42816349/copy-button-preserving-line-breaks – Bastien Robert Mar 30 '18 at 13:14
  • 1
    Possible duplicate of [javascript line break is not applying when i use document.execCommand("copy")](https://stackoverflow.com/questions/32323882/javascript-line-break-is-not-applying-when-i-use-document-execcommandcopy) – Durga Mar 30 '18 at 13:23

2 Answers2

1

Use <textarea> instead of <input> if you want to use multiline strings. Duplicated: Copy

newman
  • 424
  • 2
  • 12
0

Assuming the different pieces of <code> can be anywhere in the document…
Here is the code I ended up with:

function copyToClipboard(element) {
  var $temp = $("<textarea>");
  $("body").append($temp);
  
  var test = "";
  $(element).each(function(index, item){
    if(index > 0){
      test = test + "\n";
    }
    test = test + item.innerHTML;
  });
  
  console.log(test);
  $temp.val(test).select();
  document.execCommand("copy");
  $temp.remove();
}
code{
  display: block;
  border: 1px solid gray;
  margin: 4px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code>This is code snippet 1</code>
<code>This is code snippet 2</code>
<button onclick="copyToClipboard('code')">Copy all code</button>

Hope it helps.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47