Question

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.

Was it helpful?

Solution

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);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top