jQuery Copy to Clipboard 4 Options

Sam Deering

jquery-clipboard-copy

OK, so today i tried to use jQuery (and plain JavaScript) to automate the process of copying to clipboard which you all know can be easily done by right click > copy or by pressing CTRL+C. How copying to clipboard generally works is that you can simply call an exec copy command to get the current selection to the clipboard. However, it seems the only browser that supports this is IE. Now, we have a workaround to use a Flash SWF file to run and get the selection to the clipboard this way. There are jQuery plugins you can use and as I see it you have the following four options.

Note: My advice would be to use 3. The copy text workaround as it can be painful to try and get the other plugins working.

1. zClip

zClip only works on hyperlinks.

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

Source

2. Zero Clipboard

A pretty nifty clipboard plugin: Download Page.

function init() {
	clip = new ZeroClipboard.Client();
	clip.setHandCursor( true );
	
	clip.addEventListener('load', my_load);
	clip.addEventListener('mouseOver', my_mouse_over);
	clip.addEventListener('complete', my_complete);
	
	clip.glue( 'd_clip_button' );
}

Source

3. Copy Text Workaround

JQUERY CODE

$(document).ready(function(){
	//store nodepath value to clipboard	(copy to top of page)
	$('li').live('click', function(){
		//console.log($('#pathtonode').html()+ " copied to window");
		var path = $('#pathtonode').html();
		path = path.replace(/ > /g,".");
		//console.log(path);
		addtoppath(path);
	});
	//initially hide copy window
	$('#toppathwrap').hide();

	function addtoppath(path) {
		//console.log(path);
		$('#copypath').val(path);
		$('#toppathwrap').show();
		$('#copypath').focus();
		$('#copypath').select();
	}	
});

And for dynamic DOM elements:

$('#copypath', 'body')
	.find('a')
		.livequery('click', function() {
			$(this)
				.blur();
			//console.log('copied to copy window');
			var nodetext = $('#id-of-element-to-copy').html();
			$('#copypath input').focus();
			$('#copypath input').select();
			return false;
		});

HTML CODE

<div id="toppathwrap">
	<textarea id="copypath"></textarea>
</div>

CSS CODE

#toppathwrap { position:fixed; top:0px; right:0px; background-color:#F2F1E8; padding:5px; display:none; }

Source

4. David Walsh Tutorial

		//javascript copy function
		function copy(inElement) {
		  if (inElement.createTextRange) {
			var range = inElement.createTextRange();
			if (range &amp;&amp; BodyLoaded==1)
			 range.execCommand('Copy');
		  } else {
			var flashcopier = 'flashcopier';
			if(!document.getElementById(flashcopier)) {
			  var divholder = document.createElement('div');
			  divholder.id = flashcopier;
			  document.body.appendChild(divholder);
			}
			document.getElementById(flashcopier).innerHTML = '';
			var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+escape(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"/>';
			document.getElementById(flashcopier).innerHTML = divinfo;
		  }
		}

Source

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • andrew

    Hi, can you provide an example for option 3? I do not know how to use the code provided to copy text to the clipboard.

    • jquery4u

      @Andrew – Option 3 is a workaround for the copy text if you don’t want to use the swf options.

      I’ve implemented #3 on my JSON tool demo:
      http://www.jquery4u.com/demos/online-json-tree-viewer/

      Here is the tutorial:
      http://www.jquery4u.com/tutorials/online-json-tree-viewer/

      Hope this helps you!

      • Phoenix

        Thanks. But does it work in all browsers? And on mobiles?

        • http://www.facebook.com/oneeeeezy Justin Oneill

          @Phoneix, I too am looking for somthing that works on mobiles.. it seems that the mobiles dont like swf files very much

      • Ralf

        Sam, thanks for putting this together. Me, too, I’d like to use version 3. I already spent a lot of time on this, but totally failed to figure it out. I also failed to understand how your JSON tutorial relates to the jQuery copy function. Therefore I’d really appreciate if you could explain to us, how the code that you present here is actually used. Thank you!

        • http://jquery4u.com/ jQuery4u

          Hi Ralf, i’m writing a post which will cover the copy to clipboard (and plain text) for the code display used on the blog. This will be posted shortly and should answer your question. Sorry for the delay.

          Thanks,
          Sam

  • Pingback: JIRA: Emergencias - Cartilla Medica - Desarrollo

  • Nivaas

    Thanks for posting, i will use these codes for my blogs Online Coupon

  • Pingback: jQuery copy to clipboard, for multiple links. Integrated with ZeroClipboard javascript. Cross browser video

  • ratul Ahmed

    Is there any way to modify this code and make it usable for every browser,,,It works only with IE.,

    function ClipBoard()
    {
    if (window.clipboardData) {
    alert(“copied”);
    window.clipboardData.setData(“Text”,document.form1.reg_no.value);
    }
    }

  • Barata

    Hello, I’m on the same page as Ralf. I couldn’t understand how to implement number 3. :) I’ll be waiting for the new tutorial, hopefully soon! Thanks for your great help and all your articles!

  • Mike

    I have a question

    is i don’t want to user flash, how about do just user Javascrip or Jquery

    Thanks!!!

  • http://www.facebook.com/bretleduc Bret Leduc

    I’m on the same page as Ralf too. I want to use #3 but dont know how or where to paste the code. Is there some script src= that we need? And whats up with “And for dynamic DOM elements:”? Is that just an addition to the previous code, or do we need to put that somewhere else?

    Also – what is the script that you used on THIS page because it WORKS for me! Im using Firefox 19.0.2 on a late 2011 MacBook Pro running OSX 10.7.5 Lion.

  • Rich

    I find it incredibly funny that the solution on this page is the “Flash Solution” WTF!
    Why even write an article like this if you aren’t going to put your money where you mouth is?

    • http://jquery4u.com/ jQuery4u

      Unfortunately Rich the Flash file is needed to copy to clipboard. Maybe HTML5 can do this, if I find out I’ll post it for you.
      Sam

  • Sotabound

    Thanks Sam, I find your tutorials very helpful, especially the arrays one you did a while back, really helped me grasp the index, value using each(). Anyways don’t listen to these punks, after several hours of research yesterday, there is no easy way to do this with Javascript and sometimes you have to use Flash, which is Action Script anyways, so still cool. Flash is not quite dead yet!

    • http://jquery4u.com/ jQuery4u

      Thanks mate! :)

  • http://amir.net46.net/ Amir Mehdi

    an example is not so bad :/

  • carl lindberg

    Which ones does actually work with mobiles (non-swf) in general of these?

  • http://technoknol.blogspot.com/ Admin

    Nice Tutorial…
    but I Found that source button of “3. Copy Text Workaround” is redirecting to some other page.

    Please fix it.

    Thanks.

    Regards.
    TechnoKnol

  • Rob Hein

    For #3, I’m not clear where in the code it actually copies the text to the clipboard. It appears that it copies the html from an element into a textarea, then focuses and selects the text. Does it actually copy it to the clipboard as well?

  • Nikhilesh Jhanwar

    Can u give code for ipad …….

    all above code not working in ipad