9

In JavaScript, how can you select text on a website, copy it (by Control+C, Command+C, or Edit Copy) and have JavaScript append a line or two to the clipboard so when the user pastes, the content they copied is shown as well as the extra line?

Also, would this be possible to do only within certain <div>s of the site? If so, how?

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132

3 Answers3

10

I developed a script that does this (and here's the blog post about this):

<script>
$("body").bind('copy', function (e) {
    if (typeof window.getSelection == "undefined") return; //IE8 or earlier...

    var body_element = document.getElementsByTagName('body')[0];
    var selection = window.getSelection();

    //if the selection is short let's not annoy our users
    if (("" + selection).length < 30) return;

    //create a div outside of the visible area
    var newdiv = document.createElement('div');
    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';
    body_element.appendChild(newdiv);
    newdiv.appendChild(selection.getRangeAt(0).cloneContents());

    //we need a <pre> tag workaround
    //otherwise the text inside "pre" loses all the line breaks!
    if (selection.getRangeAt(0).commonAncestorContainer.nodeName == "PRE") {
        newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
    }

    newdiv.innerHTML += "<br /><br />Read more at: <a href='"
        + document.location.href + "'>"
        + document.location.href + "</a> &copy; MySite.com";

    selection.selectAllChildren(newdiv);
    window.setTimeout(function () { body_element.removeChild(newdiv); }, 200);
});
</script>
Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
1

You can use a combination of execCommand("Copy") and execCommand("Paste") to accomplish what you want.

This should help you out:

http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html

James Skidmore
  • 49,340
  • 32
  • 108
  • 136
  • The problem is, how can you detect when the user copies something? Then I could figure out how to do it from that page you sent me. –  Aug 01 '09 at 01:20
  • 6
    jQuery has some excellent built-in copy/paste detection: http://www.devcurry.com/2009/07/detect-copy-paste-and-cut-operations-on.html – James Skidmore Aug 01 '09 at 02:03
1

I came across this on the faqs.org site [1] and was curious too. They use some javascript from tynt.com. I also found an ask-metafilter answer [2] pointing to a different javascript. They should be good starting points. I haven't worked it out yet myself but I expect you could attach event listeners to just the div in question.

  1. http://www.faqs.org/faqs/tv/sat-night-live/deep-thoughts/
jla
  • 6,904
  • 2
  • 36
  • 34