Copying text from a document to the clipboard

Jake Howlett, 26 October 2000

Category: JavaScript; Keywords: copy range select

This is another one of those things that you will either love or hate. I love it ;-)

It only works in Internet Explorer on 32 bit Windows platforms, so is only really useful for things like Intranets, where you can be totally sure of the user's environment.

This is the script needed:

function copyText( obj ) {

/*create textRange differently
depending what the object is */
if (obj.type=="text" || obj.type=="textarea"){
var rng = obj.createTextRange();
} else {
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
}

rng.scrollIntoView();
rng.select();

if (confirm('Copy the selected text to the ClipBoard?')) rng.execCommand("Copy");
rng.collapse(false);
rng.select();

}


Now let's test it out. What better way than to copy the above function. You can paste it straight into your script file then.

The script (coloured text) is in a <span> tag with an ID of "testCopy" so we can call the function with a referrence to this span as an "object". Like this:

javascript:copyText(document.all.testCopy);

Here is an box for you to paste in to, in case you don't believe me:



You don't have to use a span for your selection. You can copy text from almost any object. For example:

Copy the first column of the fourth row of a table called "content" - copyText(document.all.content.rows(3).cells(0));

"So what!" you may be saying. "The user can easily drag over that area and copy it theirselves". Yeah, I know, but don't you think this is nice !? I'm sure you could think of a use for it somewhere...

If you want to take this idea further I suggest you get "Dynamic HTML" by Danny Goodman, listed here, and read Appendix D which has a full list of the available execCommand() methods. Which, by the way, includes "Paste".