selfprivacy.org/_vendor/github.com/google/docsy/assets/js/click-to-copy.js

48 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-04-21 23:04:16 +00:00
let codeListings = document.querySelectorAll('.highlight > pre');
2024-04-25 22:15:39 +00:00
for (let index = 0; index < codeListings.length; index++) {
2024-04-21 23:04:16 +00:00
const codeSample = codeListings[index].querySelector('code');
2024-04-25 22:15:39 +00:00
const copyButton = document.createElement('button');
const buttonAttributes = {
type: 'button',
title: 'Copy to clipboard',
'data-bs-toggle': 'tooltip',
'data-bs-placement': 'top',
'data-bs-container': 'body',
};
Object.keys(buttonAttributes).forEach((key) => {
copyButton.setAttribute(key, buttonAttributes[key]);
});
2024-04-21 23:04:16 +00:00
2024-04-25 22:15:39 +00:00
copyButton.classList.add(
'fas',
'fa-copy',
'btn',
'btn-dark',
'btn-sm',
'td-click-to-copy'
);
const tooltip = new bootstrap.Tooltip(copyButton);
copyButton.onclick = () => {
copyCode(codeSample);
copyButton.setAttribute('data-bs-original-title', 'Copied!');
tooltip.show();
};
copyButton.onmouseout = () => {
copyButton.setAttribute('data-bs-original-title', 'Copy to clipboard');
tooltip.hide();
};
2024-04-21 23:04:16 +00:00
const buttonDiv = document.createElement('div');
buttonDiv.classList.add('click-to-copy');
buttonDiv.append(copyButton);
codeListings[index].insertBefore(buttonDiv, codeSample);
}
2024-04-25 22:15:39 +00:00
const copyCode = (codeSample) => {
navigator.clipboard.writeText(codeSample.textContent.trim() + '\n');
};