0

I am looking for a way to copy the entire code block using jquery, I already have a script for copy to the clipboard which utilizes the select() method. But according to the jquery docs select event is limited to fields and boxes.

So I am seeking for a standalone solution to copy all the elements inside the codeblock at once.

This is how my HTML looks like.

<pre><code id="texttocopy" class="hljs javascript"><span class="hljs-string">'core/base.html'</span>
#some more html
</code></pre>'
<button type="button" class="btn btn-primary btnFloat" id="copybutton"></button>

Script

   $(document).ready(function () {        
            $("#copybutton").click(function () {
                console.log("clicked");

                $("#texttocopy").select();
                document.execCommand("copy");
})
Abhijeet Pal
  • 448
  • 1
  • 8
  • 21

1 Answers1

0

You can create a function to do this:

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

}

Dan Khan
  • 101
  • 2