Copying to Clipboard with Javascript

javascript
Published on June 13, 2018

Providing the feature of copying something to the OS clipboard is quite useful for the end user. The user can copy information (API keys for example) by a single click of a button, and paste that somewhere else. No dragging the mouse and selecting text !

The Selection API provides methods to programatically select a section of text. Once the text is seleted, it can be copied to clipboard with the document.execCommand() method.

Demo

1111 - 2222 - 3333 - 4444 Copied to clipboard ! Failed to copy

Selecting a Range of Text

Just like the user can select text by dragging the mouse, in the same way it is also possible to select text in a DOM element through Javascript. A range of text needs to be created from a DOM element.

<span id="key">1111-2222-3333-4444<span>
// the element whose text needs to be copied
var reference_element = document.querySelector('#key');

// create a range and set it to the contents of the reference element
var range = document.createRange();  
range.selectNodeContents(reference_element);

After the range has been created, it can be added to a Selection object. A Selection object basically represents a range of text that has been selected by the user in the current page.

In cases where the user selects text by dragging the mouse, the selected text is automatically added to the Selection object. In this case, we are explicitly adding a range of text.

// get access to Selection object via window.getSelection()
// then add a range to it
window.getSelection().addRange(range);

Copying the Selection to Clipboard

The string of text contained in the Selection object can be copied to the clipboard by executing the copy command. The document.execCommand() method executes a specific command for the current selection, in this case we need to copy the text to clipboard.

// returns true or false
var success = document.execCommand('copy');
if(success)
	console.log('Successfully copied to clipboard');
else
	console.log('Unable to copy to clipboard');

After the copy command has been executed, the range created earlier, must be deleted. Otherwise the user will see some text selected in the page. You can delete the range with the removeRange method.

window.getSelection().removeRange(range);

Complete Codes

<span id="to-select-text">1111 - 2222 - 3333 - 4444</span>
<button id="copy-button">Copy</button>
// Copy to clipboard on a click event
document.querySelector("#copy-button").addEventListener('click', function() {
	var reference_element = document.querySelector('#to-select-text');

	var range = document.createRange();  
	range.selectNodeContents(reference_element);

	window.getSelection().addRange(range);

	var success = document.execCommand('copy');
	if(success)
		console.log('Successfully copied to clipboard');
	else
		console.log('Unable to copy to clipboard');

	window.getSelection().removeRange(range);
});
In this Tutorial