DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • jQuery vs. Angular: Common Differences You Must Know
  • Better Scaffolding with jQuery - Part I
  • Electron Js + jQuery + Bootstrap - Dev to Build
  • Quickly Understand JavaScript's .forEach() vs. jQuery's .each()

Trending

  • The Systemic Process of Debugging
  • Chronicle Services: Low Latency Java Microservices Without Pain
  • Cognitive AI: The Road To AI That Thinks Like a Human Being
  • Modular Software Architecture: Advantages and Disadvantages of Using Monolith, Microservices and Modular Monolith
  1. DZone
  2. Coding
  3. JavaScript
  4. jQuery Copy to Clipboard

jQuery Copy to Clipboard

User ZeroClipboard to copy your jQuery or JavaScript code to your clipboard.

Paul Underwood user avatar by
Paul Underwood
·
Feb. 26, 14 · Tutorial
Like (0)
Save
Tweet
Share
59.53K Views

Join the DZone community and get the full member experience.

Join For Free

In a recent project I needed to create a button that would copy some text onto the user's clipboard. As I was going to build this on the click event of a button I wanted to do this with Javascript or jQuery.

After doing some research into this I found that JavaScript copy to clipboard wasn't available because of security which also meant that jQuery would not be able to copy the text to clipboard, so I had to find a different way.

After much searching I found a jQuery plugin that is hosted on Github called ZeroClipboard. This is a library that provides you with a way of coping text to your clipboard using Adobe flash and a Javascript interface. Flash can access your computers clipboard because you have to install flash and agree to the security settings, therefore we have to use flash to access the clipboard. We can use Javascript as an interface to flash so we can start this off with a click event on a button.

You can download ZeroClipboard from it's project page on Github.

ZeroClipboard

Github actually uses the ZeroClipboard project on their own site to allow you to copy the URL of the repository.

copytoclipboard

How to Use ZeroClipboard

First you need to download both the Javascript and the flash file from the ZeroClipboard repository. Then you can add this to your page by just including some Javascript files.

<html>
  <body>
    <script src="ZeroClipboard.js"></script>
    <script src="main.js"></script>
  </body>
</html>

In the main.js file you then need to create the client used in the ZeroClipboard to copy the text to the clipboard.

// main.js
var client = new ZeroClipboard( document.getElementById("copy-button"), {
  moviePath: "/path/to/ZeroClipboard.swf"
} );

client.on( "load", function(client) {
  // alert( "movie is loaded" );

  client.on( "complete", function(client, args) {
    // `this` is the element that was clicked
    this.style.display = "none";
    alert("Copied text to clipboard: " + args.text );
  } );
} );

The following examples will show you 3 different ways you can set the text to copy, you can either set the text in the Javascript, set a target area to copy the text, or set the text with a HTML data-attribute.

Set Text in Code

To set the text in the Javascript code you first new a button so that we can attach a click event.

<button id="click-to-copy">Click To Copy</button>

In the Javascript we can setup the ZeroClipboard client and set the text on the click event of the button.

First we need to setup the ZeroClipboard client and attach the movie path for the SWF file. We just need to pass in the JQuery object of the button into the constructor of the ZeroClipboard object.

var client = new ZeroClipboard( $("#click-to-copy"), {
              moviePath: "zeroclipboard/ZeroClipboard.swf",
              debug: false
} );

Using this client object we can now set the text on the click event of the ZeroClipboard button. We can use the setText() method to set the text in the Javascript code.

client.on( "load", function(client)
{
    $('#flash-loaded').fadeIn();

    client.on( "complete", function(client, args) {
        client.setText( "Set text copied." );
        $('#click-to-copy-text').fadeIn();
    } );
} );

View Demo

Set Copy Target

The copy target allows you to define a HTML element that you can get the text to copy, the value that it will use can either be the value of the element, the innerHTML or the textContent. This works off a data attribute of data-clipboard-target with a value of the ID of element you want to copy.

<button id="target-to-copy" data-clipboard-target="clipboard-text">Click To Copy</button>
<textarea name="clipboard-text" id="clipboard-text" cols="30" rows="10">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus mattis lacus nibh, ac sollicitudin sapien accumsan in. Mauris euismod posuere tellus luctus sodales.
Fusce a consectetur massa, non tincidunt mauris. Phasellus a rutrum libero. Praesent tempus urna et nisi aliquam convallis. Fusce porttitor justo condimentum orci euismod, pulvinar congue magna vestibulum.
Sed gravida eleifend justo, id ultrices tellus porttitor nec. Nam porttitor gravida tempor. In libero ante, euismod ac fermentum nec, gravida ut dolor. Nullam a pulvinar ligula.
Phasellus euismod rutrum risus non dapibus. Nullam pretium mauris vel fringilla pretium. Mauris faucibus risus vitae nulla dignissim imperdiet.
Pellentesque elementum venenatis arcu, ut bibendum risus varius nec. Fusce eu tincidunt nunc. Duis sagittis dolor congue mauris tincidunt, eu condimentum eros rhoncus.
</textarea>

We setup the ZeroClipboard client to be attached to the target-to-copy button. ZeroClipboard will search for the data-clipboard-target attribute and use this value to get the text to copy.

var clientTarget = new ZeroClipboard( $("#target-to-copy"), {
    moviePath: "http://paulund.localhost/playground/demo/zeroclipboard-demo/zeroclipboard/ZeroClipboard.swf",
    debug: false
} );

clientTarget.on( "load", function(clientTarget)
{
    $('#flash-loaded').fadeIn();

    clientTarget.on( "complete", function(clientTarget, args) {
        clientTarget.setText( args.text );
        $('#target-to-copy-text').fadeIn();
    } );
} );

This still uses the setText() method but the set it use will text that is sent through using the args.text property.

View Demo

Set Copy Text

The set copy text button will use another data attribute which will define the text to copy.

<button id="text-to-copy" data-clipboard-text="Click To Copy!">Click To Copy</button>

The Javascript that we need for this is the same as the target example, the code we need to code is placed in the args.text property, then we can use this in the setText() method to copy to the clipboard.

var clientText = new ZeroClipboard( $("#text-to-copy"), {
    moviePath: "http://paulund.localhost/playground/demo/zeroclipboard-demo/zeroclipboard/ZeroClipboard.swf",
    debug: false
} );

clientText.on( "load", function(clientText)
{
    $('#flash-loaded').fadeIn();

    clientText.on( "complete", function(clientText, args) {
        clientText.setText( args.text );
        $('#text-to-copy-text').fadeIn();
    } );
} );

View Demo

Full ZeroClipboard Documentation

For full documentation of how to use ZeroClipboard view the updated version on the Github Project page.

ZeroClipboard Documentation

JQuery JavaScript

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • jQuery vs. Angular: Common Differences You Must Know
  • Better Scaffolding with jQuery - Part I
  • Electron Js + jQuery + Bootstrap - Dev to Build
  • Quickly Understand JavaScript's .forEach() vs. jQuery's .each()

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: