Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select / Copy Text Using JavaScript or jQuery

I heard that you can't copy text (in the browser) without using something like Flash; so, is there a way to select text by using an anchor and JavaScript or jQuery.

<p>Text to be copied</p>

<a>Copy Text Above</a>
like image 425
user1658756 Avatar asked Oct 19 '12 20:10

user1658756


3 Answers

On newer browsers, you can do this to select and copy. This is a pure Javascript solution.

function copy_text(element) {
    //Before we copy, we are going to select the text.
    var text = document.getElementById(element);
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
    //add to clipboard.
    document.execCommand('copy');
}

This copy command works on all major browsers, Chrome, Firefox (Gecko), Internet Explorer, and Opera, excluding Safari.

Edit: Note for the future - While the preceding still works, there is talk about moving to the Permissions API and using the Clipboard interface, which would look like navigator.clipboard.writeText('text'). This standard is not yet finalized nor supported by many browsers. As security becomes more of a concern, expect something like this in the future.

like image 107
Zamicol Avatar answered Oct 01 '22 15:10

Zamicol


I found this jQuery solution:

$(function() {
 $('input').click(function() {
 $(this).focus();
 $(this).select();
 document.execCommand('copy');
 $(this).after("Copied to clipboard");
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="copy me!" />

Source

like image 38
DigitCart Avatar answered Oct 01 '22 15:10

DigitCart


Given the following example html:

<div class="announcementInfoText">
    <p class="copyToClipboard">
        <a id="selectAll">Select All Text</a>
    </p>
    <textarea ID="description" class="announcementTextArea">This is some sample text that I want to be select to copy to the clipboard</textarea>
</div>

you can select the text within the textarea with the following jQuery:

$("#selectAll").click(function () {
    $(this).parents(".announcementInfoText").children("textarea").select();
});

Now that the text "This is some sample text that I want to be select to copy to the clipboard" is selected, you can simply hit Ctrl+C and the text is copied to the clipboard.

like image 23
CrazyWebDeveloper Avatar answered Oct 01 '22 15:10

CrazyWebDeveloper