Skip to main content
js-tutorials.com

Simple Example of JavaScript Copy to Clipboard

Copy to clipboard help to copy content text and use to other places without right-click open context menu and click copy or CTRL + C . There are some JavaScript scripts are available on google, that provide copy to clipboard JavaScript code but that code is not compatible with some browser and some using flash.

I have found clipboard.js API for the copy to clipboard functionality with cross-browser compatibility and without flash uses. This is an awesome JavaScript library that handle copy to clipboard very gentle way.

In this tutorial, we’ll implement copy to the clipboard using clipboardjs API. This library relies on both Selection and execCommand APIs.I am following the below steps to copy input values to the clipboard and paste into the input.

You need to include clipboard.js API file into the head section of your file. You can download clipboard.js from here.

<script src="//cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js"></script>

Copy to Clipboard Using JavaScript

Step 1: Created HTML layout to show the copy input field.

<div class="row">
<h2>Copy Input Values to Clipboard</h2>
<div class="col-sm-6"><input id="txt-copy" class="form-control" type="text" value="copy this values"></div>
<button class="btn btn-primary copy-button" type="button" data-clipboard-target="#txt-copy">Copy To Clipboard</button></div>

As you can see, I used data-clipboard-target attribute to tell what you want to do with this element.data-clipboard-action attribute to specify if you want to either copy or cut content. Default would be the copy option.

Step 2: Added js code to copy input values into the clipboard.

var clipboard = new Clipboard('.btn');

Cut to Clipboard Using JavaScript

Step 1: Created HTML layout to show cut input field.

<div class="row">
<h2>Cut Input Values to Clipbord</h2>
<div class="col-sm-6"><input id="txt-cut" class="form-control" type="text" value="cut this values"></div>
<button class="btn btn-primary cut-button" type="button" data-clipboard-action="cut" data-clipboard-target="#txt-cut">Cut To Clipbord</button></div>

Step 2: Added js code to cut input values into the clipboard.

var clipboard = new Clipboard('.btn');

Clipboard Events :

<div class="row">
    <h2>Cut Input Values to Clipbord</h2>
    <div class="col-sm-6">
        <input type="text" class="form-control" id="txt-cut" value="cut this values">
    </div>
    <button type="button" data-clipboard-action="cut" data-clipboard-target="#txt-cut" class="btn btn-primary cut-button" alt="Cut to clipboard">Cut To Clipbord</button>
</div>

You can download the source code and Demo from the below link.

Leave a Reply

Your email address will not be published. Required fields are marked *