0

I've this code snippet taken form here https://stackoverflow.com/a/24631278/1447613

    $(document).on('copy', function(e) {
      var seltxt = window.getSelection();
      var copyFooter = '<br /><br />Read more: ' + document.location.href + '<br />';
      var copyHolder = $('<div>', { html: seltxt+copyFooter, style:{ position: 'absolute', left: '-99999px' } });
      $('body').append(copyHolder);
      seltxt.selectAllChildren( copyHolder[0] );
      window.setTimeout(function(){copyHolder.remove();},0);
    });

What is does is to append additional text to a selection on copy action, but it lacks two major features:

  • It copies even if we are selecting from a textarea or input field, and in my case this is not useful at all.

  • It removes the highlighted text after copy, and that's not the default behavior on browsers, so it could be annoying for users at first times.

For the first issue, I've not getting into it, as I have no idea on how to avoid the function behavior on textareas or input boxes. Luckily, someone could point me on the right direction.

As for the second issue I've tried to add this at the end:

seltxt.select();

Also tried:

seltxt.focus().select();

Both without success. Any ideas?

Community
  • 1
  • 1
BornKillaz
  • 592
  • 7
  • 19

1 Answers1

0

This should work:

$(document).on('copy', function(e) {
    var ignore = "input, textarea"
    var seltxt = window.getSelection();
    if ($(e.target).is(ignore)) {
        return;
    }
    $("<div />", {
        html: seltxt + "<br /><br />Read more: " + document.location.href + "<br />",
        appendTo: "body",
        style: {
            position: "absolute",
            left: "-99999px"
        }
    });
});
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52