3

I have a code which if I selected some text and then clicked copy it works.

My problem if I not select any text and click copy then I must copy all text.

My HTML:

<textarea id="txt" style="width:100%;height:100px;">To enjoy good health</textarea>

<div align="center"><button class="btn-md">copy</button></div>

My Script:

$(document).ready(function(){
   $('.btn-md').click(function(){
     $('#txt').focus();
     document.execCommand('copy');
   });
});
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Jsparo30
  • 405
  • 4
  • 10
  • 30
  • 1
    Read this http://stackoverflow.com/questions/34178211/text-highlighting-in-html-page/34199730?noredirect=1#comment57568955_34199730 it will help you.. – Mosh Feu Jan 24 '16 at 11:15
  • Where is the duplication? I am asking about another point which how to select all text if i not select any part of text. – Jsparo30 Jan 24 '16 at 11:40

1 Answers1

5

Try

$(document).ready(function(){

    $('.btn-md').click(function(){
        var selectedText = getSelectedText($('#txt')[0]);

        if(getSelectedText($('#txt')[0]) != '') {
          
            copyToClipboard(selectedText);
        } else {
            $('#txt').focus().select();
        }
        document.execCommand('copy');
    });
});

function getSelectedText(e) {
    var text   = "",
        start  = e.selectionStart,
        finish = e.selectionEnd;
    text   = e.value.substring(start, finish);
    return text;
}

function copyToClipboard(text){

    var et = $('<textarea/>',{
       css:{ opacity: '0' }
    });
    $('body').append(et);
    $(et)[0].value = text;
    $(et).focus().select();
    document.execCommand('copy');
    $(et).remove();

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea id="txt" style="width:100%;height:100px;">To enjoy good health</textarea>
<div align="center"><button class="btn-md">copy</button></div>
Adam Azad
  • 11,171
  • 5
  • 29
  • 70