Copying Text to the Clipboard with HTML

Author: MikeW    Date: 2016-08-15 22:25   

This is a cool tip I ran across the other day. Do you have a string you need to copy all the time like a date or an email address? Wouldn’t it be nice to embed the string in a page so it would be easy to copy to the clipboard? Due to security concerns you can’t automatically copy text to the clipboard. But, you can automatically select the text and make it really easy to copy the text.

For example, you can use the input tag to highlight text. Just click on the following input control to automatically select the text. Then use Ctr + C or Cmd + C to copy the text to the clipboard.

Here is the actual code:

1<input onclick="this.select();" type='text' value='aSampleEmailAddress@example.com' />

You can also use a textarea control.

Here is the HTML source code:

1<textarea rows="4" cols="50" onclick="this.select();">Here is some text. So you can put more text here.</textarea>

I found the example for this on lauvivan.com. Pretty useful.