Thursday, November 3, 2022

click to copy to clipboard widget via javascript

On phones (at least iPhone, probably on Android), copy and pasting is a fiddly operation. (Heck I remember when the first iPhones didn't even have copy and paste, took them a while to get the loupe ui for that right)

One convenient widget I've seen adds a "click-to-copy" widget, like here's one for branch name in git:

I whipped up a version at jsitor.com but it was a little easier to share this codepen....

Here's the JS:

const makeCopyToClipboardWidgets = () => {
  document.querySelectorAll(".click-to-copy").forEach((el, i) => {
    const widget = document.createElement('a');
    widget.innerHTML = '⧉';
    widget.className = 'click-to-copy-widget';
    widget.addEventListener("click", () =>{
      const text = el.tagName === 'A' ? el.href : el.innerText
      navigator.clipboard.writeText(text);
      widget.classList.add('active');
      setTimeout(() => { widget.classList.remove('active');}, 500)
    });
    el.after(widget);
  });
}
document.addEventListener('DOMContentLoaded', makeCopyToClipboardWidgets);

And a little CSS flavoring:

.click-to-copy {
  border: black 1px dashed;
}
.click-to-copy-widget {
  cursor: pointer;
  position: relative;
  top: -4px;
  font-weight: bolder;
  font-size: 1.2em;
}
.click-to-copy-widget.active {
  color: red;
}

So then any DOM object of class "click-to-copy" will get a border and a little icon to click:

(pardon my developer junkbox content)

Some details:
  • I dug around for the Unicode U+29C9, "Two Joined Squares" for the icon
  • I add a little "active" class and the remove it half a second later to provide some visual feedback
  • after I finished the first version, I realized a common usecase is when you want to copy a link - especially useful because it's all to easy to accidentally follow the link as you're trying to copy it on a phone. But sometimes link have a different caption than the content that is worth copying (leaving out "https://", for instance, to make it cleaner). So my code special cases A tags, and grabs the href for them instead of the text...
So, pleased with the outcome. "Vanilla JS" solutions work well for me, because there's a lot on my sites that don't have a node-ish build process... but I admit i still think a bit in terms of jQuery, so that You Might Not Need JQuery page is still a godsend, even though I haven't used jQuery in a while... it was just such a clean syntax for element selection, adding classes, and putting stuff on "ready"...


No comments:

Post a Comment