Copying text to the clipboard with JavaScript
This post describes how you can copy text to your clipboard with JavaScript.
Uses for copying text to the clipboard
If you know there is something your user will want to copy giving them an easy way can to do this can be very helpful. This is even more important when users might be on tablet or other mobile devices which selecting text is harder than using a desktop computer.
Adding to this, this feature has wider reaching accessibility uses as it means those using a screenreader or clicker to operate the browser can copy the text. Users using these devices are easily able to press buttons and navigate however selecting text is a lot tricker and in some cases impossible. Therefore adding a small button to copy the text can improve the lives of your user significantly.
However you need to make it clear what the button will do. Adding data to a users clipboard can cause frustration if it was not clear that it would occur. There may be instances where they have something important there and do not want to copy your text.
It is generally accepted that you should only add data to the clipboard if they have actively initiated it, such as by pressing a button.
Creating a function to copy text
The main copying is done by the below function.
function copyText(text) { var ta = document.createElement("textarea"); ta.value = text; ta.style.position = 'absolute'; ta.style.left = "-999999999px"; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); }
First a text area element is created and the value is set to the text we want to copy. Once created we set its positioning style elements so that once it is added to the page it will not be visible. Finally we append it to the body of the document.
Once the element is in the document we can select the content of the box using .select()
. This acts as if the user has selected the content using their mouse. Once we have done this we can use execCommand
to perform the copy.
Once this has been called we can remove the element from the page as the text has been copied.
Using this simple function we can allow copying of data to the clipboard to help the user of the website.