// copy code icon markup const copyIcon = `` // insert copy buttons for code blocks const codeBlocks = document.querySelectorAll("div.highlighter-rouge") codeBlocks.forEach((codeBlock) => { codeBlock.insertAdjacentHTML( "afterbegin", `` ) }) // handler that saves the code block innerText to clipboard function copyCodeBlock(event) { const copyButton = event.currentTarget const codeBlock = copyButton.parentElement.querySelector("pre.highlight code") const code = codeBlock.innerText.trim() // remove "$ " prompt at start of lines in code const strippedCode = code.replace(/^[\s]?\$\s+/gm, "") window.navigator.clipboard.writeText(strippedCode) // change the button text temporarily copyButton.textContent = "Copied!" setTimeout(() => copyButton.innerHTML = copyIcon, 3000) } // register event listeners for copy buttons const copyButtons = document.querySelectorAll("button.copy") copyButtons.forEach((btn) => { btn.addEventListener("click", copyCodeBlock) })