Using Panel with Javascript to make a Copy Text to Clipboard button

I am new to panel. I am trying to create a button in panel with javascript to copy text to clipboard. Usually, I would reference the id my text appears in on an HTML page and use something like this:

function myFunction() {
var copyText = document.getElementById(“myInput”);
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand(“copy”);
alert("Copied the text: " + copyText.value);
}

But since the page is create in panel, I am trying to use the same idea as is given in the “Open URL” section of the users guide button.js_on_click(args={‘target’: url}, code=‘window.open(target.value)’) (https://panel.holoviz.org/user_guide/Links.html)

I am struggling though to see how to convert the Javascript into panel. The documentation of writing Javascript in Panel is quite vague, I find.

Hi @ShanzyHolm

How to do it depends on where to copy the value from. If the value is in a Panel widget the easiest thing I could find is something like the below.

import panel as pn

def copy_to_clipboard():
    """### Copy to Clipboard Example

This example was developed as a response to
[Discourse Post 949](https://discourse.holoviz.org/t/using-panel-with-javascript-to-make-a-copy-text-to-clipboard-button/949)
by [ShanzyHolm](https://discourse.holoviz.org/u/ShanzyHolm/summary).
    """
    text = pn.pane.Markdown(copy_to_clipboard.__doc__)
    source_textarea = pn.widgets.TextAreaInput(value="Copy this text to the clipboard by clicking the button")
    copy_source_button = pn.widgets.Button(name="✂ Copy Source Value", button_type="success")
    copy_source_code = "navigator.clipboard.writeText(source.value);"
    copy_source_button.js_on_click(args={"source": source_textarea}, code=copy_source_code)
    paste_text_area = pn.widgets.TextAreaInput(value="Paste your value here")
    return pn.Column(
        text,
        pn.Row(source_textarea, copy_source_button, paste_text_area),
        name="✂ Copy to Clipboard"
    )

copy_to_clipboard().servable()

js-actions

I added the example to the gallery at awesome-panel.org. So you can check it out there.