4

I'm trying to mimic modern browsers' "copy url" functionality.

When viewing the url you don't see the http://. If you copy it to the clipboard, http:// will be added. So far I have this:

$('#address input').bind('copy', function() {
  $.fn.changevalue = function (v) {
    return $(this).val(v).trigger('change');
  }
  var origval = $(this).val();
  $(this).changevalue('http://' + origval);
});

This adds the http:// to the input field, if action 'copy' is detected but it stops the copy to clipboard. The function also adds http:// to main input field, that I don't want. I just want to add it to clipboard.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Dizzi
  • 749
  • 2
  • 11
  • 21
  • Thank you Rob Hruska for editing my questions title and post, but next time please do not remove my t.i.a line! – Dizzi Dec 14 '11 at 19:05
  • 3
    The tia is implied, it, like taglines, just clutters the questions, I wouldn't be surprised if it actually discourages users from answering. – Andrew Dec 14 '11 at 19:11

2 Answers2

3

Note: JavaScript cannot access the clipboard. Any plugin that does this usually uses Flash in the background.

To fix the copy event, after adding http:// to the input, you need to trigger the select event (not the change event). When the value is changed, the text is no longer selected, so you need to select the new text after it's edited.

To remove the http:// from the input field, you can add a setTimeout to the end of the event to reset the value.

Also, you should set $.fn.changevalue outside of the callback, it doesn't need to be re-set on each copy event.

$.fn.changevalue = function(v) {
    return this.val(v).trigger('select');  // this is already a jQuery object
}

$('#address input').bind('copy', function() {
    var $this = $(this),
    origval = $this.val();
    $this.changevalue('http://' + origval);
    setTimeout(function(){
        $this.val(origval);
    }, 0);
});

Demo: http://jsfiddle.net/TGHcD/

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0

I can't find any "copy" event in jQuery and it seems a bit tricky to make it work cross browsers.

See this thread/question for plugins and other ways to copy text to the clipboard. (Some use flash (swf files) to make it work.)

More information on the subject:

Community
  • 1
  • 1
Stefan
  • 5,644
  • 4
  • 24
  • 31