
31 Oct Cut and Copy Data to Clipboard Using jQuery
In this article, we will learn about
- How to disable Right Menu using jQuery.
- Implement Cut and Copy data Using jQuery
- Copy Url Functionality using jQuery.
In jQuery, there are plugins for creating Cut and Copy functionality for any application. But we can perform this functionality using plain jQuery only. By default, this functionality are default browser functionality though right click. So first we will disable right click functionality on browser.
1 2 3 4 5 |
$(function(){ $(document).on("contextmenu",function(e){ e.preventDefault(); }); }); |
Now implement Cut and Copy functionality using jQuery. For that let use this html code below.
1 2 3 |
<input type="text" value="Cut and Copy Data to ClipBoard" id="targetClipBoard" /> <button class="targetAction" data-type="cut" data-target-id="targetClipBoard"> Cut </button> <button class="targetAction" data-type="copy" data-target-id="targetClipBoard"> Copy </button> |
Let’s implement jQuery code for all action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$(function(){ $(".targetAction").click(function(){ var type = $(this).data('type'); var targetId = $(this).data('target-id'); if(type=='cut'){ $("#"+targetId).focus().select(); document.execCommand('cut'); } else{ $("#"+targetId).focus().select(); document.execCommand('copy'); } }); }); |
For example, we have input field and two button cut and copy to performance cut and copy features using jQuery.
Now we will create “Copy Url” feature using plain jQuery. Copy Url is common feature in many sites. Let create button to copy url.
Html Code:
1 |
<button type="button" id="copy_url" data-url="http://52.66.42.172">Copy Url</button> |
jQuery Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$("#copy_url").click(function(e){ e.preventDefault(); var targetUrl = $(this).data('url'); copyClipboardAction(targetUrl); }); function copyClipboardAction(copyValue){ // we need to create element or use existing element but should n't visible to user. var hiddenEleForCopy = $('#_hiddenEleForCopy_'); // Checking Element exists or not if(!hiddenEleForCopy.length){ $('body').append('<input style="position:absolute;top: -9999px;" id="_hiddenEleForCopy_" value=""></input>'); hiddenEleForCopy = $('#_hiddenEleForCopy_'); } hiddenEleForCopy.val(copyValue); hiddenEleForCopy.select(); document.execCommand('copy'); document.getSelection().removeAllRanges(); } |
By using above functionality, we will create Cut and Copy functionality using jQuery.
No Comments