Xah Talk Show 2024-07-30 Ep568, JavaScript Coding, Add a Copy Paste Button for Source Code

vidthumb  8vK3PA5mn8

steps overview:

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);
  });
}