11

I'm familiar with ZeroClipboard and jquery.copy, which both use Flash. OK, so I get it, for browser security reasons, copying is disallowed and we need Flash. But this means the copying functionality does not work in mobiles (iPhone, Android) or iPad.

Is there any resource or plugin that allows a simple Copy to Clipboard functionality on both modern browsers (include IE7+) and mobile browsers?

Thanks!

PKHunter
  • 682
  • 2
  • 13
  • 28

3 Answers3

15

There is not a great solution to do this without using flash. I would just keep it simple and allow your users to copy the text themselves. It's how google serves their analytics code to users to embed on their sites. I'm sure if there was a great way to do it that google would be using it.

Keeping it simple:

$(function(){
    $('.text').click(function(){
        $(this).select();
    });
});

Focus event: http://jsfiddle.net/khXjC/

Click event: http://jsfiddle.net/qjfgoeLm/

RoggA
  • 503
  • 1
  • 4
  • 15
tlaverdure
  • 522
  • 7
  • 18
  • 6
    You have to do the `.select()` on `.click()` rather than focus. On focus triggers first and then click so the text will highlight but then the caret will appear and the text deselects. – roborourke Apr 04 '14 at 09:46
  • Thanks, focus used to work when I first posted this, but I guess browsers have changed since 2012. – tlaverdure Jul 02 '15 at 11:53
  • Just found this whilst looking at copy element methods* after seeing the copied content doesn't go to droid clipboard from a how to+, or even msdn's copy method... So is there currently nothing available that works on windows And android? *browser flags / extensions / console? +https://www.dannyguo.com/blog/how-to-add-copy-to-clipboard-buttons-to-code-blocks-in-hugo/ – Jonny Jun 23 '21 at 08:11
4

I just wanted to offer an update, since there have been some recent developments on this front. Modern browsers, except for Safari support copying via JS, using the execCommand() api.

Assuming you build your UI to gracefully degrade to manual copying for Safari, you could implement copy-to-clipboard on the rest of them. Presumably, Safari will include support for this eventually.

Look at https://clipboardjs.com/ and http://www.sitepoint.com/javascript-copy-to-clipboard/ for options.

Browsers supported, as of writing: Chrome 42+, Firefox 41+, IE 9+, Opera 29+.

sersun
  • 847
  • 1
  • 7
  • 17
0

const input_field = document.getElementById( 'input_field' )
function yourFunction(){
   input_field.select();// select the input field
   input_field.setSelectionRange(0,99999);// For mobile devices
   navigator.clipboard.writeText( input_field.value )

}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 13 '22 at 07:56