1

I've seen several sites that when you copy and paste text from their website, it turns out something like this:

<text here> - From <website name here>

And I am wondering how to do that. I have tried using the alt parameter and others. Thanks in advance.

tjhorner
  • 351
  • 2
  • 16
  • Here is one: http://www.metrolyrics.com/radioactive-lyrics-imagine-dragons.html. Yes I know that there's a little [ From: http://www.metrolyrics.com/radioactive-lyrics-imagine-dragons.html ] but at the end of it, when I copy and paste it, it says "Read more: (blah blah)" – tjhorner Jun 15 '13 at 23:18
  • Have you tried checking the JavaScript function causing it in your console? – dsgriffin Jun 15 '13 at 23:24

1 Answers1

0

This is not so simple as it would seem to be. I've done this before so I will show you how to do it using jquery and the rangy selection library (https://code.google.com/p/rangy/)

Basically you do this:

  • take the current selection
  • copy it in some invisible element
  • add your text on that element
  • select the invisible element
  • restore the selection state with a setTimeout

Here's a fiddle and the code:

http://jsfiddle.net/P4yfw/

$("body").on("copy", function() {
    var selection = rangy.getSelection();
    var ranges = selection.getAllRanges();
    var container = $("<div>");

    for (var i = 0; i < ranges.length; i++)
        container.append(ranges[i].cloneContents());

    container.append(" - whatever text you want to append");

    var wnd = $(window);
    var scrollTop = wnd.scrollTop();
    var scrollLeft = wnd.scrollLeft();

    var offscreen = $("<div>").css({
        position: "absolute",
        left: "-1000px",
        width: "1px",
        height: "1px",
        overflow: "hidden"
    }).appendTo("body");

    offscreen.css({ top: scrollTop });
    offscreen.append(container);

    selection.selectAllChildren(container[0]);
    event.stopPropagation();

    setTimeout(function() {
        selection.setRanges(ranges);
        offscreen.detach(); // offscreen.remove() will remove events attached to the original elements (not cloned elements) on IE8
        wnd.scrollTop(scrollTop);
        wnd.scrollLeft(scrollLeft);
    }, 0);
});
urraka
  • 997
  • 7
  • 9
  • Note: the scroll stuff is there because of some issues on IE8, where the scroll would change when changing the selection. – urraka Jun 15 '13 at 23:33