Skip to content

Instantly share code, notes, and snippets.

@grace-snow
Created October 8, 2020 12:07
Show Gist options
  • Save grace-snow/aa6d524f054690f92f345dca895b4bd6 to your computer and use it in GitHub Desktop.
Save grace-snow/aa6d524f054690f92f345dca895b4bd6 to your computer and use it in GitHub Desktop.
A jQuery snippet to copy text on button click, with the button wording briefly changing to give feedback to the user. NOTE: for modern browsers, there are simpler ways to do this. This solution needed to be jQuery and work in IE.
/**************************************
* Copy text (jQuery)
*/
/*
* HOW TO USE:
* 1. Select text: <span id="[unique id of text to be copied]">[text to copy]</span>
* 2. Run script on next button: <button type="button" class="button button--link-style" onClick="copyToClipboard($('#[id of text to be copied]'))" aria-label="Copy [text or description of text to be copied] to your clipboard">Copy</button>
*/
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
var $btn = $(element).next(); // selects next button to the text. HTML order is important here
$btn.text("Copied!");
setTimeout(function() {
$btn.text("Copy");
}, 1500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment