Autoselectable textareas

Sometimes it's useful to provide text or code to users so that they can copy and paste it elsewhere. This might be an embeddable code snippet, a generated license key, or maybe a recipe. What's being copied doesn't matter so much, but how you allow users to copy it does.

A common way to allow users to copy text is in a readonly textarea:

<textarea readonly>Lorem ipsum dolor sit amet</textarea>

While users can select the text in these regions, the UX leaves much to be desired. To improve the experience, it's helpful to automatically select the text in the textarea.

Many examples on the internet use something along the lines of:

//DON'T DO IT THIS WAY!
$('textarea').click(function (e) {
    this.select();
    e.preventDefault();
});

Every time a users tries to select the text, it'll refocus the entire textarea.

The right way to autoselect the text in the textarea is to use the focus event so that the text is selected only on the initial focus:

$('textarea[readonly]').on('focus', function () {
    this.select();
});

And, of course, if you're not using jQuery it's only a few more lines of code:

Array.from(document.querySelectorAll('textarea[readonly]'))
    .forEach(function (node) {
        node.addEventListener('focus', function () {
            this.select();
        }, false);
    });

On Chrome

Chrome used to have issues with this technique, and a myriad of answers include notes about how to work around Chrome's buggy mouseup behavior, which would cancel the selection. Fortunately, the bug has been fixed.

If you must support older versions of Chrome, you can use something along the lines of:

$('textarea[readonly]').on('focus', function (e) {
    this.select();
    this.focus();

    $(this).off('.autoselect').one('mouseup.autoselect', function (e) {
        e.preventDefault();
    });
});