Skip to content

Commit

Permalink
fix: proper handling of multiple tabs for the copy button
Browse files Browse the repository at this point in the history
fixes davidsneighbour/kollitsch.dev#849

Signed-off-by: Patrick Kollitsch <[email protected]>
  • Loading branch information
davidsneighbour committed May 7, 2024
1 parent 40611ca commit 311f1da
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions modules/renderhooks/assets/js/plugins/clipboard.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-ignore - is mounted via gohugo module
import ClipboardJS from '../libs/clipboard';

// initiate clipboard.js on all buttons with class .btn-clipboard
Expand All @@ -19,3 +20,44 @@ clipboard.on('success', (/** @type {{ clearSelection: () => void; }} */ event) =

// handling errors
clipboard.on('error', (/** @type {any} */ event) => { });

// handle copy button on multi-tab highlighting components
if (document.readyState === 'loading') { // if loading hasn't finished yet
document.addEventListener('DOMContentLoaded', setupCopyButton);
} else { // `DOMContentLoaded` has already fired
setupCopyButton();
}
function setupCopyButton() {
// all .component--highlight blocks
const highlightComponents = document.querySelectorAll('.component--highlight');
highlightComponents.forEach(component => {
// copy buttons within this component (in case there are multiple)
const copyButtons = component.querySelectorAll('.btn-clipboard');
if (copyButtons.length > 0) {
// update the copy button's target for each button
function updateClipboardTarget(newTarget) {
if (newTarget) {
copyButtons.forEach(copyButton => {
copyButton.setAttribute('data-clipboard-target', newTarget);
});
} else {
console.error('No new target specified.');
}
}
// Add event listeners to all tab buttons within this block, excluding the copy button
component.querySelectorAll('.nav-link:not(.btn-clipboard)').forEach(tabButton => {
tabButton.addEventListener('click', () => {
const newTarget = tabButton.getAttribute('data-bs-target');
updateClipboardTarget(newTarget);
});
});
// Set initial clipboard target to the currently active tab within this block
const activeTabButton = component.querySelector('.nav-link.active:not(.btn-clipboard)');
if (activeTabButton) {
updateClipboardTarget(activeTabButton.getAttribute('data-bs-target'));
}
} else {
console.error('.btn-clipboard button(s) not found in the component.');
}
});
}

0 comments on commit 311f1da

Please sign in to comment.