Copy Element to Clipboard Using Javascript

Over the years I’ve built a web based system that controls most of the sales and support aspects for my software. This includes tracking sales, editing sales, supplying customers with registration keys, prompting them to renew support, and so on. There’s also a search interface that allows me to find customer sales details, registration keys, and to check if they have current support. I use this search interface multiple times a day and when I need to find a registration key or need to remind a customer that their support has expired the system outputs the email text I need to send to the customer to the browser window. Then I select it, and paste it into my emails.

This morning I thought it would be really neat if I could cut out the select and copy steps and have JavaScript copy it into the clipboard for me. Last time I checked this (5 years ago) it wasn’t possible without Flash. Now it turns out you can use the Web API that most modern browsers support to do it.

I wrote this little JavaScript function that I can pass a HTML element ID to and it copies the contents to the clipboard.

function copyToClipboard(elem)
{
	//create a new range to hold the DIV to copy
	var range = document.createRange();
	//select the not containing the element to copy
	range.selectNode(elem);
	//clear the current selection
	window.getSelection().removeAllRanges();
	//add the selected range to the current selection
	window.getSelection().addRange(range);
	//run exeCommand to copy 
	document.execCommand('copy');
	//clear the selection
	window.getSelection().removeAllRanges();
}

The key here is the document.execCommand(‘copy’) call which sends the contents of the element to the clipboard so I can paste it into my email tool. Triggering the function is pretty simple with something like this:

document.getElementById('copy-link').addEventListener('mousedown',copyToClipboard("element-id"));

I found a couple of other solutions that copied to the clipboard by copying the element contents to temporarily created <textarea> but the issue with this was that the HTML formatting was not copied. I needed this so that my support emails maintained my standard CSS styling.

This entry was posted in Software on by .

About markn

Mark is the owner and founder of Timesheets MTS Software, an mISV that develops and markets employee timesheet and time clock software. He's also a mechanical engineer, father of four, and a lifelong lover of gadgets.