Copy text to clipboard button

Someone mentioned this and thought it’d be a really cool little add on. This code is to add a button to copy text for your customers and can be linked to any field in a details section.

Screenshot 2023-05-10 at 22.00.53

You just need to add the view and field number

Javascript

$(document).on('knack-view-render.view_22', function() {
  var $button = $('<button class="copyText">Copy</button>');
  $('.field_10 .kn-detail-body').prepend($button);
  
  $button.click(function() {
    var $input = $('<input>');
    var copiedText = $('.field_10 .kn-detail-body span').text();
    
    $input.val(copiedText);
    $('body').append($input);
    $input.select();
    
    document.execCommand('copy');
    
    $input.remove();
    $button.html('Copied ✅');
  });
});

CSS

.copyText {
  margin:10px 0px!important;
  background:rgb(33, 136, 214);
  color:white;
  font-weight: bold;
  border-radius:.6em;
  padding:5px 7px;
  border:none!important;
  cursor:pointer;
}

Any questions just leave them below

6 Likes

Brilliant, thank you!

2 Likes

Great! But how I can find these view and field numbers?

Nevermind, I’ve managed to find the numbers. However, the code copies the CSS code and not the text in the field.

@Bruno have you added the correct field number? can you show me your code

1 Like

Thanks John! It works really well.

Can I change the word copy by a icon?

Hi Johnny, the code is running but a curious thing happens: instead of just “ABC” it copies “ABCABCABC”, i.e. the text 3x (!)

The javascript for this app is:

// ---- This fixes the issue with some Squarespace templates ignoring clicks on some links ----

$(document).on(‘knack-page-render.any’, function(event, page) {
if ($(‘html’).hasClass(‘squarespace-damask’)) {
$(‘.kn-content a’).not(‘[href^=“http”],[href^=“https”],[href^=“mailto:”]’).each(function() { $(this).attr(‘href’, function(index, value) { if (value && value.length > 0 && value.substr(0,1) !== “/”) {
return (window.location.protocol + ‘//’ + window.location.host + window.location.pathname + value); }}); }); } });

// ---- Insert copy to clipboard button ----

$(document).on(‘knack-view-render.view_62’, function() {
var $button = $(‘Copy’);
$(‘.field_107 .kn-detail-body’).prepend($button);

$button.click(function() {
var $input = $(‘’);
var copiedText = $(‘.field_107 .kn-detail-body span’).text();

$input.val(copiedText);
$('body').append($input);
$input.select();

document.execCommand('copy');

$input.remove();
$button.html('Copied ✅');

});
});

Thanks

Bruno

Here could be the fix @Bruno

change this
var copiedText = $(‘.field_107 .kn-detail-body span’).text();
to this adding :last-child
var copiedText = $(‘.field_107 .kn-detail-body span:last-child’).text();

Knack has had this issue for years a where updates to the field create duplicate span tags for the field

Thanks Johnny, but the problem persists… -Bruno

Curiously, execCommand is automatically crossed out in the code…

Hi @Bruno

I guess the code you copied in latest reply is the code you still can’t get to work. It doesn’t show the line I suggested you update from my last reply adding ‘:last-child’

var copiedText = $(‘.field_107 .kn-detail-body span:last-child’).text();

I think this is why

Ops, my mistake. This is the corrected code, and it`s unfortunately not working:

$(document).on(‘knack-view-render.view_62’, function() {
var $button = $(‘Copy’);
$(‘.field_107 .kn-detail-body’).prepend($button);

$button.click(function() {
var $input = $(‘’);
var copiedText = $(‘.field_107 .kn-detail-body span:last-child’).text();

$input.val(copiedText);
$('body').append($input);
$input.select();

document.execCommand('copy');

$input.remove();
$button.html('Copied ✅');

});
});

@bruno Had run up a brand new app and copied the code original code and it works fine. I copied your code here and it came up with loads of errors this is because this normal text uses “smart quotes” (‘’ ) rather than regular single quotes ('') needed for code. When you put the code in your posts half of it was normal text and the other half in quotes code, I wonder if you copied this back in then added the changes ie ‘:last-child’ but it still couldn’t read your code based on the text format issue as above.

I get your point about document.execCommand(‘copy’); this is because it’s being phased out so have improved the code. I have added in your field numbers so just copy this code below.

$(document).on('knack-view-render.view_62', function() {
  var $button = $('<button class="copyText">Copy</button>');
  $('.field_107 .kn-detail-body').prepend($button);
  
  $button.click(function() {
    var copiedText = $('.field_107 .kn-detail-body span:last-child').text();
    
    navigator.clipboard.writeText(copiedText).then(function() {
      $button.html('Copied ✅');
    }, function(err) {
      console.error('Failed to copy text: ', err);
    });
  });
});

You

Thanks for the effort Johnny, but it is still not working. Please check the pasted copy below regarding quotes, chatgpt says it’s ok hehehe

$(document).on(‘knack-view-render.view_62’, function() {
var $button = $(‘Copy’);
$(‘.field_107 .kn-detail-body’).prepend($button);

$button.click(function() {
var copiedText = $(‘.field_107 .kn-detail-body span:last-child’).text();

navigator.clipboard.writeText(copiedText).then(function() {
  $button.html('Copied ✅');
}, function(err) {
  console.error('Failed to copy text: ', err);
});

});
});

I will post my screen, hope this helps. I’m having a hardtime posting code!

@bruno do you want to email me and get it sorted
johnny@appknowledged.co.uk

// Variable pour vérifier si la valeur a été copiée
var isValueCopied = false;

// Fonction pour ajouter le bouton et gérer l’action de copie
function addCopyButton() {
// Vérifier si le bouton a déjà été ajouté
if ($(‘.view_653 .field_874 .kn-detail-body .copyText’).length === 0) {
var $button = $(‘Copy’);
$(‘.view_653 .field_874 .kn-detail-body’).append($button);

// Gérer l'événement de clic du bouton pour effectuer l'action de copie
$button.on('click', function() {
  if (!isValueCopied) {
    var copiedText = $('.view_653 .field_874 .kn-detail-body span:last-child').text();

    navigator.clipboard.writeText(copiedText).then(function() {
      $button.html('Copied ✅');
      isValueCopied = true;
    }, function(err) {
      console.error('Failed to copy text: ', err);
    });
  }
});

}
}

// Attendez que la page soit rendue
$(document).on(‘knack-view-render.view_653’, function(event, page) {
if ($(‘html’).hasClass(‘squarespace-damask’)) {
$(‘.kn-content a’).not(‘[href^=“http”],[href^=“https”],[href^=“mailto:”]’).each(function() {
$(this).attr(‘href’, function(index, value) {
if (value && value.length > 0 && value.substr(0,1) !== “/”) {
return (window.location.protocol + ‘//’ + window.location.host + window.location.pathname + value);
}
});
});
}

// Ajouter le bouton après un délai de 100 ms pour s’assurer que la page est complètement chargée
setTimeout(addCopyButton, 100);
});

// Gérer l’action de copie lors du clic sur le texte
$(document).on(‘click’, ‘.view_653 .field_874 .kn-detail-body’, function() {
if (!isValueCopied) {
var copiedText = $(‘.view_653 .field_874 .kn-detail-body span:last-child’).text();

navigator.clipboard.writeText(copiedText).then(function() {
  isValueCopied = true;
}, function(err) {
  console.error('Failed to copy text: ', err);
});

}
});

This looks great Johnny, though I need this in a grid view, not in a details view.

Can it be modified for field in a grid?

Any guidance kindly appreciated !

thanks.
Calvin.

@Calvin_B - not seen JP on the forum for a while.

Here is the code that is working for me in a Details View:

// Add a Copy button to custom value field fieldkey
	// Function to add the button and handle the copy action correctly scoped
	function addCopyButton() {
		$('.view_698 .field_760 .kn-detail-body').each(function () {
			// Check if the button has already been added to this instance
			if ($(this).find('.copyText').length === 0) {
				var $button = $('<button class="copyText">Copy</button>');
				// Append the button correctly within each container, ensuring it's placed after the content
				$(this).append($button);

				// Correctly scope the click event to this button
				$button.on('click', function (event) {
					// Prevent the event from affecting other elements
					event.stopPropagation();

					// Target the text within the same container as the clicked button
					var copiedText = $(this).siblings('span').last().text(); // Adjusted to ensure correct text is targeted

					navigator.clipboard.writeText(copiedText).then(() => {
						$(this).text('Copied ✅'); // Ensure 'this' is correctly used to change the button text
						// No need to manage isValueCopied here unless it's used for other logic outside this function
					}).catch((err) => {
						console.error('Failed to copy text: ', err);
					});
				});
			}
		});
	}
1 Like