ethanrusz/assets/js/clipboard.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-01-29 18:38:53 -05:00
/*
* A nice little clipboard script provided by Crykn. Thanks!
2023-10-24 16:11:51 -04:00
*/
function sleep(ms) {
2024-01-29 18:38:53 -05:00
return new Promise((resolve) => setTimeout(resolve, ms));
2023-10-24 16:11:51 -04:00
}
async function onClickEffect(btn, style) {
2024-01-29 18:38:53 -05:00
btn.removeClass("btn-light");
btn.addClass(style);
await sleep(250);
btn.removeClass(style);
btn.addClass("btn-light");
2023-10-24 16:11:51 -04:00
}
2024-01-29 18:38:53 -05:00
$(document).ready(function () {
// Create button
$(".page__content pre > code").each(function () {
$(this)
.parent()
.prepend(
$(document.createElement("button"))
.prop({
type: "button",
innerHTML: '<i class="far fa-copy"></i>',
})
.attr("title", "Copy to clipboard")
.addClass("btn")
.addClass("btn--primary")
.css("position", "absolute")
.css("right", "1em")
// Click listener
.on("click", function () {
let codeElement = $(this).parent().children("code").first();
2023-10-24 16:11:51 -04:00
2024-01-29 18:38:53 -05:00
if (!codeElement) {
throw new Error(
"Unexpected error! No corresponding code block was found for this button."
);
}
2023-10-24 16:11:51 -04:00
2024-01-29 18:38:53 -05:00
// Blink effect
onClickEffect($(this), "btn--success");
2023-10-24 16:11:51 -04:00
2024-01-29 18:38:53 -05:00
// Copy to clipoard function
navigator.clipboard.writeText($(codeElement).text()).then(
() => true,
() => true
);
return true;
})
);
});
2023-10-24 16:11:51 -04:00
});