Last active
August 1, 2022 13:08
-
-
Save jmarreros/d6fb68d0801412fcb887d1a4a7e467ce to your computer and use it in GitHub Desktop.
Copy text to clipboard using jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Container with class: "copy" | |
copy the text after the ":" character | |
var copyImg has the img path | |
*/ | |
(function( $ ) { | |
'use strict'; | |
// Append copy image to text | |
$('.copy').filter(function(){ | |
if ( $(this).text().includes(':') ) { | |
$(this).append(`<img class="copy-img" src="${copyImg}" width=20 height=20 style="display:inline-block;cursor:pointer">`); | |
} | |
}); | |
$('.copy-img').click(function(){ | |
const wrapCopy = $(this).parent('.copy'); | |
const completeText = $(wrapCopy).text(); | |
// validation | |
if ( $(wrapCopy).find('small').length ) return; | |
const firstText = completeText.split(':')[0]; | |
const copyText = completeText.replace(firstText, '').replace(':','').trim(); | |
// copy clipboard function | |
copyToClipboard(copyText); | |
// show temporay message | |
$(wrapCopy).append('<small id="tmp-msg"> copiado</small>'); | |
setTimeout(function(){ | |
$(wrapCopy).find('#tmp-msg').remove(); | |
}, 1000); | |
}); | |
// Auxiliar function to copy clipboard | |
function copyToClipboard(textToCopy) { | |
if (navigator.clipboard && window.isSecureContext) { | |
navigator.clipboard.writeText(textToCopy); | |
} else { | |
const temp = $("<input>"); | |
$("body").append(temp); | |
temp.val(textToCopy).select(); | |
document.execCommand('copy'); | |
temp.remove(); | |
} | |
} | |
})( jQuery ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment