feat(article): copy button for highlight block (#295)

This button only shows on highlighted code blocks, because it uses the wrapper div.highlight
This commit is contained in:
Jimmy Cai
2021-08-08 18:15:27 +02:00
committed by GitHub
parent 4a0cbac234
commit 24915a912f
2 changed files with 58 additions and 0 deletions
+32
View File
@@ -54,6 +54,38 @@ let Stack = {
observer.observe(articleTile)
}
/**
* Add copy button to code block
*/
const codeBlocks = document.querySelectorAll('.article-content .highlight');
const copyText = `Copy`,
copiedText = `Copied!`;
codeBlocks.forEach(codeBlock => {
const copyButton = document.createElement('button');
copyButton.innerHTML = copyText;
copyButton.classList.add('copyCodeButton');
codeBlock.appendChild(copyButton);
const pre = codeBlock.getElementsByTagName('pre');
const code = pre[0].textContent;
copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(code)
.then(() => {
copyButton.textContent = copiedText;
setTimeout(() => {
copyButton.textContent = copyText;
}, 1000);
})
.catch(err => {
alert(err)
console.log('Something went wrong', err);
});
});
});
new StackColorScheme(document.getElementById('dark-mode-toggle'));
}
}