1

To copy a value to the clipboard, i use this function:

$(function() {
   $('.copy-to-clipboard input').click(function() {
      $(this).focus();
      $(this).select();
      document.execCommand('copy');
   $(".copied").text("Link copied to clipboard").show().fadeOut(1200);
   });
});


<div class='copied'></div>

<div class="copy-to-clipboard"> 
   <input type="text" value="Text to grab" /> 
</div>

how can i achieve the same with the value in betweeen span tags like below:

<div class="copy-to-clipboard"> 
   <span>Text to grab</span>
</div>
Jack Maessen
  • 1,610
  • 3
  • 15
  • 34
  • Please see [this](https://stackoverflow.com/questions/36639681/how-to-copy-text-from-a-div-to-clipboard/51261023) and [this](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – weegee Feb 06 '19 at 18:13

2 Answers2

1

You can create an input element with the value of the text in the span copy text and remove the input automatically

$(function() {
   $('.copy-to-clipboard > span').click(function() {
     var a=$('.copy-to-clipboard > span').text();
     var t=a.split(" ").join('');
    $('.copy-to-clipboard > span').append('<input value='+t+'>')
    
    $('input').select();
  
      document.execCommand('copy');
       $('.copy-to-clipboard > span > input').remove()
   
   $(".copied").text("Link copied to clipboard").show().fadeOut(1200);
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="copy-to-clipboard"> 
   <span>Text to grab</span>
</div>
ellipsis
  • 11,498
  • 2
  • 13
  • 33
-1

$('.copy-to-clipboard input').click(function()

change to

$('.copy-to-clipboard span').click(function()

should work

ThGz
  • 11
  • 5