Copy text to clipboard button

Has anyone gotten this to work yet for a grid/table?

1 Like

Not me.

What alternatives exist for users who cannot utilize a “Copy text to clipboard” button?

We have this working in grids details views. If you can bear with me for 12hrs I’ll post what we have done here.
Craig

Here you go:

This needs to be added to the CSS pane in the builder:

.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;
}

This is the function that will apply a button to a specific field in a details view:

function addCopyButton(viewId, fieldId) {
        var $button = $('<button class="copyText">Copy</button>');
        var $fieldBody = $(`#${viewId} .field_${fieldId} .kn-detail-body`);

        $fieldBody.append($button);
        
        $button.click(function() {
            var copiedText = $fieldBody.find('span').first().text().trim();
            navigator.clipboard.writeText(copiedText);
            $(this).html('Copied ✅');
            setTimeout(() => {
                $(this).html('Copy');
            }, 2000);
        });
    }

This is how to call the function:

//replace view_5959 with your view_xxx
$(document).on('knack-view-render.view_5959', function(event, {key: viewId}) {
        //Replace the number in the second parameter with the number that follows field_
        addCopyButton(viewId, 2320);
 });

Hope this helps

Craig

Hi @Tyler

We didn’t use a button on grids as it looks messy. We didn’t need to copy all the data in a cell just some of it.

This is what we did:

We created a text formula with a span in the text like this:

image

You can put as much information as you want inside the span and you can use different classes as long as the classes in the code match. you could also add an icon after the span to say which part gets copied i.e:

image

Here is the JavaScript which you’ll need to copy into the javascript pane of the builder:

$(document).on("knack-view-render.any", function (event, view) {
      const clicktoCopy = $(`#${viewId} .ca-click-to-copy`);

        if (clicktoCopy.length > 0) {

            $('.ca-click-to-copy').closest('td').on("click", function () {
                const cell = $(this);
                const spanToCopy = cell.find('.ca-click-to-copy');
                const text = $.trim(spanToCopy.text());

                navigator.clipboard.writeText(text);
            });
        }
});

We also have a function that shows a message when the text has been copied which I’ll be happy to give to you if you need it but it’s quite specific to our needs. I’ll try and come up with something a bit more generic for the forum.

Hope this helps

Craig