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:

$('textarea').click(function (e) {;

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 () {;

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

    .forEach(function (node) {
        node.addEventListener('focus', function () {
        }, 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).off('.autoselect').one('mouseup.autoselect', function (e) {