Use Javascript to Copy to the Clipboard

I’ve found it very useful to be able to copy web-content to the clipboard. For example, to generate boiler plate text in my online customer management system and paste it into Outlook for emailing. I’ve needed to use it a few times over the last couple of years and my go-to reference has usually been this Stack Overflow post. It basically comes down to whether or not a browser supports execCommand(‘copy’), if it does then you’re set. In it’s most basic form you can copy the content of a DIV with something like this:

function copyToClipboard(element_to_copy){
    //create an input range object to hold the DIV to copy
    var range = document.createRange();
    //select the node containing the element to copy
    range.selectNode(element_to_copy);
    //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();
}

This method uses the input range object which can hold HTML values. It’s a HTML5 object and not supported in IE9 and earlier. The function is creating a new Range object, loading the content of the element we want to copy, clearing the current selection of all other ranges, adding the new range to the selection and then running execCommand(‘copy’) to put the contents into the clipboard.

Here’s a variation I’ve used that creates an input field temporarily to hold the content we want to copy. This is useful as it has wider support that that used above as it doesn’t rely on the Range object. Care must be taken, however, to replace single quotes with ' before putting content into the value attribute of the input.

function copyToClipboard(element_id) {
  var input_placeholder = document.createElement("input");
  input_placeholder.setAttribute("value", document.getElementById(element_id).innerHTML);
  document.body.appendChild(input_placeholder);
  input_placeholder.select();
  document.execCommand("copy");
  document.body.removeChild(input_placeholder);
}  
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.