Skip to content

Commit

Permalink
πŸ› fix copy multiline and line number bug
Browse files Browse the repository at this point in the history
  • Loading branch information
mickm3n committed Jul 28, 2024
1 parent 88fa91f commit 171d1ca
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions static/js/copy-code-button.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// This script adds copy buttons to all pre > code elements
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('pre > code').forEach((codeBlock) => {
const container = codeBlock.parentNode;
Expand All @@ -8,7 +7,17 @@ document.addEventListener('DOMContentLoaded', (event) => {
copyButton.innerText = 'Copy';

copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(codeBlock.innerText).then(
// Get all the table rows
const rows = codeBlock.querySelectorAll('table tr');
// Extract only the text content from each row, ignoring the line numbers
const codeText = Array.from(rows)
.map(row => {
const codePart = row.querySelector('td:nth-child(2)');
return codePart ? codePart.textContent : '';
})
.join('');

navigator.clipboard.writeText(codeText).then(
() => {
copyButton.innerText = 'Copied!';
setTimeout(() => {
Expand Down

0 comments on commit 171d1ca

Please sign in to comment.