How can I create a button that copies text to clipboard?

How can I create a button that copies text to clipboard?

Laskquestion
Tourist
8 0 3

How do I code a button that will copy specific text to the clipboard?

For example: <p>DISCOUNTCODE</p>, customer will click on the button, and the <p>DISCOUNTCODE</p> will be copied to the user clipboard so he/she can paste it on checkout.

Replies 2 (2)

vincenttriola
Shopify Partner
15 1 6

Hello, I was working on a similar issue, so I thought I would post my solution. I used java to create a citation for blog articles. I am unsure where you will use your code but this may help if you are in the liquid.

<p id="sample">your conent to be copied</p>
<a class="btn btn--tertiary btn--small" href="#" onclick="CopyToClipboard('sample');return false;">Copy</a>
<script>
function CopyToClipboard(id)
{
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
</script>

You can see an example of it here at the bottom of the page https://vincenttriola.com/blogs/ten-years-of-academic-writing/hr-s-role-in-public-private-sector

macadelic
Visitor
2 0 6

Did you figure this out? I need this as a possible workaround for Dawn's silly placement of the discount code prompt in checkout.