Improve copy button script formatting

This commit is contained in:
Em (Ethan) Ruszanowski 2024-01-29 18:38:53 -05:00
parent d5d4df98a8
commit d7010dafd1
Signed by: em
GPG key ID: C725D6E571252B96

View file

@ -1,9 +1,9 @@
/* /*
* A nice little clipboard script provided by crykn. Thanks! * A nice little clipboard script provided by Crykn. Thanks!
*/ */
function sleep(ms) { function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
} }
async function onClickEffect(btn, style) { async function onClickEffect(btn, style) {
@ -14,32 +14,40 @@ async function onClickEffect(btn, style) {
btn.addClass("btn-light"); btn.addClass("btn-light");
} }
$(document).ready(function() { $(document).ready(function () {
// Create butons // Create button
$(".page__content pre > code").each(function() { $(".page__content pre > code").each(function () {
$(this).parent().prepend( $(this)
$(document.createElement('button')).prop({ .parent()
type: 'button', .prepend(
$(document.createElement("button"))
.prop({
type: "button",
innerHTML: '<i class="far fa-copy"></i>', innerHTML: '<i class="far fa-copy"></i>',
}) })
.attr('title', 'Copy to clipboard') .attr("title", "Copy to clipboard")
.addClass('btn') .addClass("btn")
.addClass('btn--primary') .addClass("btn--primary")
.css('position', 'absolute') .css("position", "absolute")
.css('right', '1em') .css("right", "1em")
// Click listener // Click listener
.on('click', function() { .on("click", function () {
let codeElement = $(this).parent().children('code').first(); let codeElement = $(this).parent().children("code").first();
if (!codeElement) { if (!codeElement) {
throw new Error("Unexpected error! No corresponding code block was found for this button."); throw new Error(
"Unexpected error! No corresponding code block was found for this button."
);
} }
// Blink effect // Blink effect
onClickEffect($(this), "btn--success") onClickEffect($(this), "btn--success");
// Copy to clipoard function // Copy to clipoard function
navigator.clipboard.writeText($(codeElement).text()).then(() => true, () => true); navigator.clipboard.writeText($(codeElement).text()).then(
() => true,
() => true
);
return true; return true;
}) })
); );