0

I have one div with an article and I want to get particular lines from that article and copy it in clipboard for that I have made some code which is below

$(document).ready(function(){
 $.fn.renderedText = function(){
   var o = s = this.text();
   while (s.length && this[0].scrollHeight >  this.innerHeight()){
     s = s.slice(0,-1);
     this.text(s+"…");
   }
   this.text(o);
   return s;
 };

 $(".event_button").click(function(){  
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($('.dummy').renderedText()).select();
      document.execCommand("copy");
      console.log($temp);
      $temp.remove();
    
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dummy" style="display: -webkit-box; overflow: hidden; text-overflow: ellipsis; -webkit-line-clamp: 2; -webkit-box-orient: vertical;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nisl tincidunt eget nullam non. Quis hendrerit dolor magna eget est lorem ipsum dolor sit. Volutpat odio facilisis mauris sit amet massa. Commodo odio aenean sed adipiscing diam donec adipiscing tristique. Mi eget mauris pharetra et. Non tellus orci ac auctor augue. Elit at imperdiet dui accumsan sit. Ornare arcu dui vivamus arcu felis. Egestas integer eget aliquet nibh praesent. In hac habitasse platea dictumst quisque sagittis purus. Pulvinar elementum integer enim neque volutpat ac.Senectus et netus et malesuada. Nunc pulvinar sapien et ligula ullamcorper malesuada proin. Neque convallis a cras semper auctor. Libero id faucibus nisl tincidunt eget. Leo a diam sollicitudin tempor id. A lacus vestibulum sed arcu non odio euismod lacinia. In tellus integer feugiat scelerisque. Feugiat in fermentum posuere urna nec tincidunt praesent. Porttitor rhoncus dolor purus non enim praesent elementum facilisis. Nisi scelerisque eu ultrices vitae auctor eu augue ut lectus. Ipsum faucibus vitae aliquet nec ullamcorper sit amet risus. Et malesuada fames ac turpis egestas sed. Sit amet nisl suscipit adipiscing bibendum est ultricies. Arcu ac tortor dignissim convallis aenean et tortor at. Pretium viverra suspendisse potenti nullam ac tortor vitae purus. Eros donec ac odio tempor orci dapibus ultrices. Elementum nibh tellus molestie nunc. Et magnis dis parturient montes nascetur. Est placerat in egestas erat imperdiet. Consequat interdum varius sit amet mattis vulputate enim.Sit amet nulla facilisi morbi tempus. Nulla facilisi cras fermentum odio eu. Etiam erat velit scelerisque in dictum non consectetur a erat. Enim nulla aliquet porttitor lacus luctus accumsan tortor posuere.  </div>


<button><span data-value="copyText" id="copyText" class="event_button button btn cpytxt">Copy</span></button>

but my copy code is not working.

that means sometimes copytext is working some time it is not.

sometimes when I click 2-3 on the copy button then it copies once.

can anybody help me with this.

Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23
  • where is the `.button_span` class?? – Ankit Singh Dec 26 '19 at 05:06
  • @AnkitSingh sorry for the inconvenience I have updated my code which is not working –  Dec 26 '19 at 05:10
  • I've checked your code and its working fine for me? check with a alert message if you have any doubt that your code is running or not. – Ankit Singh Dec 26 '19 at 05:23
  • @AnkitSingh yes problem exactly the same I think copy function is running firstly and after that renderedText() is running and if I set alert then renderedText() get more time to execute so result is showing properly –  Dec 26 '19 at 05:25
  • @NiketJoshi I am exactly said it is working sometimes sometimes not –  Dec 26 '19 at 05:27

4 Answers4

0

Better your HTML must be like :

<span data-value="copyText" id="copyText" class="event_button button btn button_span active cpytxt">
      <button>Copy</button>
</span>

And Script be like :

<script>
$(document).ready(function(){
    $.fn.renderedText = function(){
      var o = s = this.text();
      while (s.length && this[0].scrollHeight >  this.innerHeight()){
        s = s.slice(0,-1);
        this.text(s+"…");
      }
      this.text(o);
      return s;
    };

    $(".button_span.active").on('click', function(event){ 
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($('.dummy').renderedText()).select();
        document.execCommand("copy");
        console.log($temp);
        $temp.remove();
        console.log('copied!')
    });
});

</script>

If you want to work them immediately on load, you can add $(".button_span.active").click(). But if you have multiple items on a page. this will try to copy every element and only the last one will be there inactive clipboard.

Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65
jerinisready
  • 936
  • 10
  • 24
  • @YashwardhanPauranik I have updated code which is almost same as your answer but it is not working –  Dec 26 '19 at 05:14
  • @MNJ I have confirmed this working in mty ubuntu firefox before posting. Could you share mode details?> – jerinisready Dec 26 '19 at 11:28
0

For the solution Either you can check the By Click Here or you can follow below code that i have added, i have checked in my local machine and it working fine while testing.

 <div id="div_1">
     This is the first content we want to select and copy to the clipboard.
 </div>
 <a id="div_1" href="#" name="copy_pre">Copy Contents</a>

  <div id="div_2">
    This is the second content we want to select and copy to the clipboard.
  </div>
  <a id="div_2" href="#" name="copy_pre">Copy Contents</a>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> 
  </script>

 <script >
    $(document).ready(function(){
       $("a[name=copy_pre]").click(function() {
           var id = $(this).attr('id');
           var el = document.getElementById(id);
           var range = document.createRange();
           range.selectNodeContents(el);
           var sel = window.getSelection();
           sel.removeAllRanges();
           sel.addRange(range);
           document.execCommand('copy');
           alert("Contents copied to clipboard.");
           return false;
        });
      });
  </script>

I Really Hope this will helps you to solve out your problem! :).

Niket Joshi
  • 739
  • 5
  • 23
0

Try this one it should work as you want it should be. I just putted some line of code outside of block which will be executed after click.

$(document).ready(function(){
 $.fn.renderedText = function(){
   var o = s = this.text();
   while (s.length && this[0].scrollHeight >  this.innerHeight()){
     s = s.slice(0,-1);
     this.text(s+"…");
   }
   this.text(o);
   return s;
 };
  
    //Array variable for generate random strings
    var sentences= [
    'so fat not even Dora can explore her',
    'so  fat I swerved to miss her and ran out of gas',
    'so smelly she put on Right Guard and it went left',
    'so fat she hasn’t got cellulite, she’s got celluheavy',
    'so fat she don’t need no internet – she’s already world wide',
    'so hair her armpits look like Don King in a headlock',
    'so classless she could be a Marxist utopia',
    'so fat she can hear bacon cooking in Canada',
    'so fat she won “The Bachelor” because she all those other bitches',
    'so stupid she believes everything that Brian Williams says',
    'so ugly she scared off Flavor Flav',
    'is like Domino’s Pizza, one call does it all',
    'is twice the man you are',
    'is like Bazooka Joe, 5 cents a blow',
    'is like an ATM, open 24/7',
    'is like a championship ring, everybody puts a finger in her'
    ];

    var $temp = '';
    $('#generate_btn').on('click', function(){
      var index= Math.floor(Math.random() * (sentences.length));
      $('.dummy').text(sentences[index]);
      
      $temp = $("<input style='position:absolute;top:-10000px;'>");
      $("body").append($temp);
      $temp.val($('.dummy').renderedText());
    });

 $(".event_button").click(function(){  
      if($temp!=''){
        $temp.select();
        document.execCommand("copy");
        console.log($temp.val());
       }else{
        alert("Please click generate");
       }
    
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="generate_btn">generate</button>

<div class="dummy" style="display: -webkit-box; overflow: hidden; text-overflow: ellipsis; -webkit-line-clamp: 2; -webkit-box-orient: vertical;"></div>


<button><span data-value="copyText" id="copyText" class="event_button button btn cpytxt">Copy</span></button>
Ankit Singh
  • 1,477
  • 1
  • 13
  • 22
0

please try this

function copyToClipboard(text) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(text).select();
  document.execCommand("copy");
  $temp.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my_text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut lab222</div>

<button id="copy" onclick="copyToClipboard($('.my_text').text())">copy</button>
Alfarouq
  • 173
  • 1
  • 6