_hyperscript icon indicating copy to clipboard operation
_hyperscript copied to clipboard

How could we copy a component's text to the clipboard with HTMX?

Open cbmeeks opened this issue 1 year ago • 2 comments

I have two large text fields and it would be really cool to have an HTMX button to copy the contents to the clipboard. I can do this in vanilla JS but was wondering if there is some clever way to do this using inline HTMX.

Any suggestions?

Thanks.

cbmeeks avatar Apr 02 '24 18:04 cbmeeks

Since you were asking for HTMX:

<span hx-on:click="!window.s?s=this.textContent:null;navigator.clipboard.writeText(s);this.textContent='Copied';setTimeout(()=>{this.textContent=s}, 1000)">WriteMeBabyOneMoreTime</span>

This makes sure not to copy "Copied" to the clipboard when the text was replaced.

andryyy avatar Apr 03 '24 05:04 andryyy

Just in case you were wondering how to do this in hyperscript (as this is the hyperscript repo), you can see an example on the hyperscript homepage with the CDN link.

<div>
  <code style="border: 2px dotted #00000055; margin: 0 10px; padding: 4px 6px; border-radius: 4px">&lt;script src="https://unpkg.com/[email protected]"&gt;&lt;/script&gt;</code>
  
  <button style="font:inherit;font-size:.8em;background:#3465a4;color:white;border:none;padding: 0 .4em; border-radius: .4em" _="on click
    writeText(my previousElementSibling's innerText) on navigator.clipboard
    put 'copied!' into me
    wait 1s
    put 'copy' into me">copy</button>
</div>

devalexwhite avatar Apr 11 '24 14:04 devalexwhite