Xah Talk Show 2024-07-30 Ep568, JavaScript Coding, Add a Copy Paste Button for Source Code
steps overview:
- use JavaScript to add a “copy” button.
- use JavaScript to add a event handler to the copy button.
- the event handler will attach a function.
- the function will copy the text inside the pre tag to operating system clipboard.
note, this won't work if not on https
console.log( 3 )
{ // 2024-07-30 // add a button to all pre tags // clicking the button copies the pre tag text const xpreTags = document.getElementsByTagName("pre"); Array.from(xpreTags, (x) => { const xbutton = document.createElement("button"); xbutton.setAttribute("type", "button"); xbutton.setAttribute("class", "xNytKh"); xbutton.innerText = "Copy Code"; x.insertAdjacentElement("beforebegin", xbutton); }); const f_do_copy = (xevent) => { const xtt = xevent.target.nextElementSibling; navigator.clipboard.writeText(xtt.innerText); }; const xbuttonlist = document.getElementsByClassName("xNytKh"); Array.from(xbuttonlist, (x) => { x.addEventListener("click", f_do_copy, false); }); }