Copy text to your clipboard using Javascript

In my current job, I tend to spend a fair amount of time copying a string of information from a website, and then pasting it to another place. More often than not though, I’m not copying a line of text directly of a page, but rather a conglomerate of information I stick together using other Javascript calls. Because I’m lazy efficient, I relegate all of this to simple “copy” buttons.

This can be achieved using a simple Javascript function:

function copyToClipboard(parentElement, string) {

//parentElement is the containing element, this can be any element, but most browsers default behaviour is to scroll to this element, which isn't a very nice effect
//string is the string you want to copy to the clipboard
var copyDiv = document.createElement('div');
copyDiv.id = "copyDiv";
copyDiv.contentEditable = true;
parentElement.appendChild(copyDiv);
copyDiv.innerHTML = string;
copyDiv.unselectable = "off";
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
parentElement.removeChild(copyDiv);

}

You can add this to any element as per normal:

document.getElementById("this").addEventListener("click", function() {

copyToClipboard(this, this.innerHTML);

});

Here is an example that takes a table of first and last names, and copies “X’s last name is Y” to your clipboard.

Jill Smith
Eve Jackson
John Doe

Leave a Reply

Your email address will not be published. Required fields are marked *