doc-fui-ds
Version:
Doc
51 lines (41 loc) • 1.9 kB
JavaScript
// Function to remove the leading space from the first line and trim content
function cleanCode(code) {
const lines = code.split('\n');
lines[0] = lines[0].trim(); // Remove leading space from the first line
return lines.join('\n').trim();
}
// Dynamically find all code elements with code tag or defin tag with class(code.className)
const codeElements = document.querySelectorAll('code');
codeElements.forEach(codeElement => {
const exampleId = codeElement.id;
const template = document.getElementById(`html-${exampleId}`);
if (template) {
let code = template.innerHTML.trim();
// Clean up the code content before inserting
code = cleanCode(code);
// Populate the code block with cleaned code
codeElement.textContent = code;
// Highlight the code using highlight.js
hljs.highlightElement(codeElement);
}
});
// Function to copy code to clipboard and update the button text and icon
function copyCode(exampleId, btn) {
const codeElement = document.getElementById(exampleId);
const code = codeElement.textContent;
const textarea = document.createElement('textarea');
textarea.value = code;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
// Change text and icon to "Copied"
btn.innerHTML = '<i class="bi bi-clipboard-check"></i> Copied!';
// Apply the 'copied' class for green background
btn.classList.add('copied');
// Optionally reset the button text and icon after a few seconds
setTimeout(() => {
btn.innerHTML = '<span class="fui-cursor-pointer"><i class="bi bi-clipboard"></i> Copy</span>';
btn.classList.remove('copied');
}, 2000); // Reset after 2 seconds
}