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');
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With