Skip to content

Instantly share code, notes, and snippets.

@jmarreros
Last active August 1, 2022 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmarreros/d6fb68d0801412fcb887d1a4a7e467ce to your computer and use it in GitHub Desktop.
Save jmarreros/d6fb68d0801412fcb887d1a4a7e467ce to your computer and use it in GitHub Desktop.
Copy text to clipboard using jquery
/*
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