panel icon indicating copy to clipboard operation
panel copied to clipboard

Document how to select a specific html element of a Panel component

Open MarcSkovMadsen opened this issue 2 years ago • 1 comments

With Panel 1.x the html elements are inside shadowroot and cannot be selected via document.getElementBy....

Thus I don't know how to answer users looking to something using javascript where they need to select a specific html element.

For example as asked in https://discourse.holoviz.org/t/direct-input-focus-to-a-specific-text-input-widget/5836.

Reference Example

import panel as pn

pn.extension(design="bootstrap")

text_input = pn.widgets.TextInput(name="Input", css_classes=["text-input"])

submit = pn.widgets.Button(name="Submit")
script = pn.pane.HTML(margin=0, width=0, height=0, sizing_mode="fixed")

def run_script(code):
    script.object = "<script>" + code + "</script>"
    script.object = ""

layout = pn.Column(
    text_input, submit, script
)

@pn.depends(submit, watch=True)
def handle_submit(_):
    code="console.log('hello')"
    run_script(code)    
    
layout.servable()

In the above example I would like to replace the line code="console.log('hello')" with something that selects the <input> element. Then I can use js to give it focus

MarcSkovMadsen avatar Aug 06 '23 17:08 MarcSkovMadsen

Hello @MarcSkovMadsen, With the following code, when you click on the submit button, you get focus on the text_input

import panel as pn

pn.extension(design="bootstrap")

text_input = pn.widgets.TextInput(name="Input", css_classes=["text-input"])

submit = pn.widgets.Button(name="Submit")
submit.js_on_click(
    args={"text_input": text_input},
    # code="console.log(Bokeh.index.query_one((view) => view.model.id == text_input.id))",
    code="Bokeh.index.query_one((view) => view.model.id == text_input.id).input_el.focus()",
)


layout = pn.Column(text_input, submit)


layout.servable()

The solution come from https://discourse.bokeh.org/t/retrieving-html-element-linked-to-bokeh-js-object-from-bokeh-documents-in-javascript/11313/7

etihwo avatar May 29 '25 17:05 etihwo