Select / Copy Text Using JavaScript or jQuery

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.


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


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.