Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy link of an anchor tag to clipboard when clicking on it

Tags:

jquery

This is the code that I have used to show some of the data. In this code, I am having anchor tag and I want to copy the link of that anchor tag when clicking on it. This is the code I have used as below:

<div class="search_item_list clearfix" id="response">
   <?php foreach($jobs as $job){
   ?>
    <a class="copy_text"  data-toggle="tooltip" title="Copy to Clipboard" 
       href="<?=base_url().'home/company_profile_detail?id='.$job['company_id'];?>"><span class="icon link"><i class="fa fa-link"></i></span>Copy Link</a>
    <?php } ?>
</div>

<script>
   $(".copy_text").click(function(e){
      e.preventDefault();
      var button = $(this);
      var text = button.attr("href");
      text.select();
      $(document).execCommand("copy");
      alert("Copied the text ");
   })
</script>

I am getting the jQuery as

text.select is not a function.

like image 429
Arun Sharma Avatar asked Nov 19 '18 06:11

Arun Sharma


1 Answers

try below code snippet

$('.copy_text').click(function (e) {
   e.preventDefault();
   var copyText = $(this).attr('href');

   document.addEventListener('copy', function(e) {
      e.clipboardData.setData('text/plain', copyText);
      e.preventDefault();
   }, true);

   document.execCommand('copy');  
   console.log('copied text : ', copyText);
   alert('copied text: ' + copyText); 
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <a class="copy_text"  data-toggle="tooltip" title="Copy to Clipboard" href="home/company_profile_detail">Copy Link</a>
like image 60
Shiv Kumar Baghel Avatar answered Sep 22 '22 15:09

Shiv Kumar Baghel