pub.solar/scripts/copy-code.js

38 lines
839 B
JavaScript
Raw Normal View History

(() => {
const findLanguage = (el) => {
if (el.lang) {
return el.lang;
}
if (el.parentElement) {
return findLanguage(el.parentElement);
}
return 'en';
}
const codeInPreElements = document.querySelectorAll('section pre code');
codeInPreElements.forEach((element) => {
const lang = findLanguage(element);
const button = document.createElement('button');
const resetButtonText = () => {
button.innerHTML = { en: 'Copy', de: 'Kopieren' }[lang];
}
button.className = 'ps-copy-code-button';
button.addEventListener('click', () => {
navigator.clipboard.writeText(element.innerHTML);
button.innerHTML = { en: 'Copied!', de: 'Kopiert!' }[lang];
setTimeout(resetButtonText, 1000);
});
resetButtonText();
element.after(button);
});
})();