Created
October 8, 2020 12:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************** | |
* 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