# How to dispatch JS events properly in Gradio app?

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-dispatch-js-events-properly-in-gradio-app%2F150600%3E%5C
**Category:** Beginners\
**Created:** [April 15, 2025, 10:34am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-dispatch-js-events-properly-in-gradio-app%2F150600 "2025-04-15T10:34:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![luchd](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/luchd/32/45543_2.png) [@luchd](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fluchd)%5C
**Post date:** [April 15, 2025, 10:34am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-dispatch-js-events-properly-in-gradio-app%2F150600%2F1 "2025-04-15T10:34:41Z")

</div>

Hi friends,

I’m new to Gradio, and I’m building an app with the layout of 2 columns:

- The left column is a chatbot
- The right one is like a glossary

The workflow is when a user chats with the bot, they can highlight text and click on a floating “Show” button to show the selected term in the glossary.

My trouble is when the “Show” button clicked, I want to invoke a Python function with the selected term passed in to handle some logic before returning the output to be attached to the glossary. I don’t know how to implement this properly.

The following code is what I’ve tried so far, it does capture the highlighted text, but clicking the “Show” button doesn’t do anything while I expect it should dispatch some events to simulate Gradio events, hence triggering handlers.

```python
with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(
                type="messages"
            )
            state = gr.State(value=[])
            txt = gr.Textbox(
                placeholder="Type your answer here…",
                visible=True
            )
            demo.load(init_chat, inputs=None, outputs=[chatbot, state])
            txt.submit(generate_chat_completion, inputs=[txt, state], outputs=[chatbot, state, txt])

        with gr.Column(scale=1):
            glossary = gr.Markdown("Glossary will appear here...")

    selected_term = gr.Textbox(visible=False, elem_id="selected_term")
    selected_term.submit(fn=show_term, inputs=selected_term, outputs=glossary)

    js_script = """
    async () => {
        globalThis.setupShowButton = () => {
            // Create the floating button and attach to body
            if (!document.getElementById("show-btn")) {
                const showBtn = document.createElement("button");
                showBtn.id = "show-btn";
                showBtn.textContent = "Show";
                showBtn.style.display = "none";
                showBtn.style.position = "absolute";
                showBtn.style.zIndex = "999999";
                showBtn.style.background = "#2563eb";
                document.body.appendChild(showBtn);

                showBtn.addEventListener("click", () => {
                    const term = showBtn.getAttribute("data-selection");
                    const textbox = document.querySelector('#selected_term');
                    if (textbox) {
                        textbox.value = term;
                        const inputEvent = new Event("input", { bubbles: true });
                        textbox.dispatchEvent(inputEvent);

                        const keyboardEvent = new KeyboardEvent("keydown", {
                            bubbles: true,
                            cancelable: true,
                            key: "Enter",
                            code: "Enter"
                        });
                        textbox.dispatchEvent(keyboardEvent);
                        showBtn.style.display = "none";
                    }
                });
            }

            const showBtn = document.getElementById("show-btn");

            document.addEventListener("mouseup", function () {
                const selection = window.getSelection().toString().trim();
                if (!selection) {
                    showBtn.style.display = "none";
                    return;
                }
                try {
                    const range = window.getSelection().getRangeAt(0);
                    const rect = range.getBoundingClientRect();
                    showBtn.style.display = "block";
                    showBtn.setAttribute("data-selection", selection);
                } catch (err) {
                    console.warn("Range error:", err);
                }
            });
        };
        setTimeout(globalThis.setupShowButton, 100);
    }
    """
    demo.load(None, None, None, js=js_script)

return demo

```

Any help would be much appreciated. Thanks so much for your support!

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2FJohn6666)%5C
**Post date:** [April 15, 2025, 12:07pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-dispatch-js-events-properly-in-gradio-app%2F150600%2F2 "2025-04-15T12:07:21Z")

</div>

Gradio is convenient, but it’s not very flexible…

There is a dedicated Gradio question channel on HF Discord, so if you can ask your questions there, I recommend that.

> <https://github.com/gradio-app/gradio/issues/2981>
>
> \### Describe the bug
> 
> The only way we've found so far to edit a gradio textarea …from javascript is to create an "input" event.
> 
> The code below demonstrates this: left button just sets textarea content from javascript, right button sets content and creates an event, and bottom button copies textarea contents to label via gradio.
> 
> If you press left and then bottom button, the text "abc" is not copied to label. If you press right and then bottom button, the text "def" is copied to label. So the event is necessary.
> 
> The problem is whenever the event is sent I get a very unpleasant looking exception stack trace in browser. Since everything is obfuscated, I don't want to fix it myself client-size since then I'd have to exit the fix every time I update gradio.
> 
> \### Is there an existing issue for this?
> 
> \- \[X\] I have searched the existing issues
> 
> \### Reproduction
> 
> \`\`\`python
> import gradio as gr
> 
> with gr.Blocks(analytics\_enabled=False) as demo:
> text = gr.TextArea(label="Copy from", elem\_id="elem")
> label = gr.Label(label="Copy to")
> with gr.Row():
> set\_text\_without = gr.Button('Set text via Javascript without event')
> set\_text\_with = gr.Button('Set text via Javascript with event')
> go = gr.Button('Copy text from textarea into label', variant="primary")
> 
> set\_text\_without.click(
> fn=lambda: None,
> \_js="""
> function(){
> elem = document.getElementsByTagName('gradio-app')\[0\].shadowRoot.querySelector('#elem textarea')
> elem.value = "abc"
> return \[\]
> }
> """,
> inputs=\[\],
> outputs=\[\],
> )
> 
> set\_text\_with.click(
> fn=lambda: None,
> \_js="""
> function(){
> elem = document.getElementsByTagName('gradio-app')\[0\].shadowRoot.querySelector('#elem textarea')
> elem.value = "def"
> elem.dispatchEvent(new Event("input", { bubbles: true }));
> return \[\]
> }
> """,
> inputs=\[\],
> outputs=\[\],
> )
> 
> go.click(
> fn=lambda x: x,
> inputs=\[text\],
> outputs=\[label\],
> )
> 
> demo.queue().launch(share=False)
> \`\`\`
> 
> 
> \### Screenshot
> 
> \_No response\_
> 
> \### Logs
> 
> \`\`\`shell
> Uncaught (in promise) TypeError: R is null
> v index.0b923826.js:76
> result index.0b923826.js line 75 \> AsyncFunction:7
> anonymous index.0b923826.js line 75 \> AsyncFunction:10
> ac index.0b923826.js:34
> Nt index.0b923826.js:76
> ae index.0b923826.js:4
> ae index.0b923826.js:4
> \_ Button.svelte:10
> ae index.0b923826.js:4
> ae index.0b923826.js:4
> B Button.svelte:9
> Z index.0b923826.js:1
> m Button.svelte:14
> ct index.0b923826.js:4
> m Button.svelte:14
> ct index.0b923826.js:4
> m index.0b923826.js:34
> ct index.0b923826.js:4
> m index.0b923826.js:34
> m index.0b923826.js:34
> m index.0b923826.js:34
> m Row.svelte:10
> ct index.0b923826.js:4
> m index.0b923826.js:34
> ct index.0b923826.js:4
> m index.0b923826.js:34
> m index.0b923826.js:34
> m index.0b923826.js:34
> m Column.svelte:13
> ct index.0b923826.js:4
> m index.0b923826.js:34
> ct index.0b923826.js:4
> m index.0b923826.js:74
> p index.0b923826.js:75
> Rl index.0b923826.js:4
> mt index.0b923826.js:4
> promise callback\*so index.0b923826.js:4
> zl index.0b923826.js:4
> ctx index.0b923826.js:4
> xc index.0b923826.js:76
> promise callback\*xc/\< index.0b923826.js:76
> promise callback\*xc index.0b923826.js:76
> Tt index.0b923826.js:4
> kc index.0b923826.js:76
> ml index.0b923826.js:77
> connectedCallback index.0b923826.js:77
> w0 index.0b923826.js:77
> \<anonymous\> index.0b923826.js:77
> index.0b923826.js:76:20397
> \`\`\`
> \`\`\`
> 
> 
> \### System Info
> 
> \`\`\`shell
> gradio-3.15.0 (and same in gradio-3.16.1), Windows 10, python 3.10.6
> \`\`\`
> 
> 
> \### Severity
> 
> annoying

> <https://github.com/gradio-app/gradio/issues/8688>
>
> I was making my own Bounding Box editor in gradio and succeeded to make some wit…h written JS and HTML code using canvas, but now i need to pass an information from JS where boxes are drawn and saved to gr.Dataframe, how do i do it ?
> 
> \`\`\`
> import gradio as gr
> 
> js\_script = """
> const values = \[
> {
> "x\_min": 115,
> "y\_min": 24,
> "x\_max": 329,
> "y\_max": 61
> },
> {
> "x\_min": 51,
> "y\_min": 60,
> "x\_max": 363,
> "y\_max": 105
> },
> {
> "x\_min": 120,
> "y\_min": 107,
> "x\_max": 277,
> "y\_max": 135
> }
> \];
> """
> 
> with gr.Blocks(js=js\_script) as demo:
> bounding\_box\_editor = gr.HTML()
> boxes\_list = gr.Dataframe(headers=\["x\_min", "y\_min", "x\_max", "y\_max"\], datatype=\["number", "number", "number", "number"\], interactive=False, col\_count=(4, 'fixed'))
> demo.launch(share=False)
> \`\`\`
>         
> P.S. If there is already a solution to a good bounding box drawer and editor (with drawing, deleting, resizing options) - I would appreciate a link
