# HTML

```python
gradio.HTML(···)
```

### Description

Creates a component with arbitrary HTML. Can include CSS and JavaScript to create highly customized and interactive components.

### Behavior

### Initialization

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `value` | `Any \| Callable \| None` | `None` | The HTML content in the ${value} tag in the html_template. For example, if html_template="<p>${value}</p>" and value="Hello, world!", the component will render as `"<p>Hello, world!</p>"`. |
| `label` | `str \| I18nData \| None` | `None` | The label for this component. Is used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to. |
| `html_template` | `str` | `"${value}"` | A string representing the HTML template for this component as a JS template string and Handlebars template. The `${value}` tag will be replaced with the `value` parameter, and all other tags will be filled in with the values from `props`. This element can have children when used in a `with gr.HTML(...):` context, and the children will be rendered to replace `@children` substring, which cannot be nested inside any HTML tags. |
| `css_template` | `str` | `""` | A string representing the CSS template for this component as a JS template string and Handlebars template. The CSS will be automatically scoped to this component, and rules outside a block will target the component's root element. The `${value}` tag will be replaced with the `value` parameter, and all other tags will be filled in with the values from `props`. |
| `js_on_load` | `str \| None` | `"element.addEventListener('click', function() { trigger('click') });"` | A string representing the JavaScript code that will be executed when the component is loaded. The `element` variable refers to the HTML element of this component, and can be used to access children such as `element.querySelector()`. The `trigger` function can be used to trigger events, such as `trigger('click')`. The value and other props can be edited through `props`, e.g. `props.value = "new value"` which will re-render the HTML template. If `server_functions` is provided, a `server` object is also available in `js_on_load`, where each function is accessible as an async method, e.g. `server.list_files(path).then(files => ...)` or `const files = await server.list_files(path)`. The `upload` async function can be used to upload a JavaScript `File` object to the Gradio server, returning a dictionary with `path` (the server-side file path) and `url` (the public URL to access the file), e.g. `const { path, url } = await upload(file)`. The `watch` function can be used to observe prop changes when the component is an output to a Python event listener: `watch('value', () => { ... })` runs the callback after the template re-renders whenever `value` changes, or `watch(['value', 'color'], () => { ... })` to watch multiple props.`. |
| `apply_default_css` | `bool` | `True` | If True, default Gradio CSS styles will be applied to the HTML component. |
| `every` | `Timer \| float \| None` | `None` | Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer. |
| `inputs` | `Component \| list[Component] \| set[Component] \| None` | `None` | Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. |
| `show_label` | `bool` | `False` | If True, the label will be displayed. If False, the label will be hidden. |
| `visible` | `bool \| Literal['hidden']` | `True` | If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM |
| `elem_id` | `str \| None` | `None` | An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
| `elem_classes` | `list[str] \| str \| None` | `None` | An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
| `render` | `bool` | `True` | If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. |
| `key` | `int \| str \| tuple[int \| str, ...] \| None` | `None` | in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. |
| `preserved_by_key` | `list[str] \| str \| None` | `"value"` | A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor. |
| `min_height` | `int \| None` | `None` | The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If HTML content exceeds the height, the component will expand to fit the content. |
| `max_height` | `int \| None` | `None` | The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the component will scroll. |
| `container` | `bool` | `False` | If True, the HTML component will be displayed in a container. Default is False. |
| `padding` | `bool` | `False` | If True, the HTML component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is False. |
| `autoscroll` | `bool` | `False` | If True, will automatically scroll to the bottom of the component when the content changes, unless the user has scrolled up. If False, will not scroll to the bottom when the content changes. |
| `buttons` | `list[Button] \| None` | `None` | A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. |
| `head` | `str \| None` | `None` | A raw HTML string to inject into the document `<head>` before `js_on_load` runs. Typically used for `<script>` and `<link>` tags to load third-party libraries. Scripts are deduplicated by `src` and links by `href`, so multiple components requiring the same library won't load it twice. |
| `server_functions` | `list[Callable] \| None` | `None` | A list of Python functions that can be called from `js_on_load` via the `server` object. For example, if you pass `server_functions=[my_func]`, you can call `server.my_func(arg1, arg2)` in your `js_on_load` code. Each function becomes an async method that sends the call to the Python backend and returns the result. |
| `props` | `Any` | `` | Additional keyword arguments to pass into the HTML and CSS templates for rendering. |
### Shortcuts

| Class | Interface String Shortcut | Initialization |
|-------|--------------------------|----------------|
| `gradio.HTML` | `"html"` | Uses default values |
### Demos

**super_html**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/super_html)

```python
import os
import gradio as gr


with gr.Blocks() as demo:
    gr.Markdown("""
    # Simple HTML usecase
    This is the classic `gr.HTML` usecase where we just want to render some static HTML.
    """)
    simple_html = gr.HTML("<h1 style='color:purple;' id='simple'>Hello, World!</h1>")

    gr.Markdown("""
    # Templated HTML usecase
    'value' can now be anything, and it can be used inside the `html_template` using `${value}` syntax.
    Note that when used as output or input, `value` is just this specific value rather than the entire HTML.
    """)
    with gr.Row():
        name1 = gr.Textbox(label="Name")
        templated_html = gr.HTML(
            "",
            html_template="<h1>Hello, {{value}}! ${value.length} letters</h1>",
            elem_id="templated",
        )
        name1.change(lambda x: x, inputs=name1, outputs=templated_html)

    gr.Markdown("""
    # Additional Props
    You are not limited to using `${value}` in the templates, you can add any number of custom tags to the template, and pass them to the component as keyword arguments. These props can be updated via python event listeners as well.
    """)
    with gr.Row():
        templated_html_props = gr.HTML(
            "John",
            html_template="""
                <h1 style="font-size: ${fontSize}px;">Hello, ${value}!</h1>
            """,
            fontSize=30,
            elem_id="props",
        )
        slider = gr.Slider(10, 100, value=30, label="Font Size")
        slider.change(
            lambda x: gr.HTML(fontSize=x), inputs=slider, outputs=templated_html_props
        )

    gr.Markdown("""
    # CSS Templating
    We can also template CSS, which is automatically scoped to the component.
    """)
    with gr.Row():
        name2 = gr.Textbox(label="Person")
        color = gr.ColorPicker(label="Text Color", value="#00ff00")
        bold = gr.Checkbox(label="Bold Text", value=True)
        templated_html_css = gr.HTML(
            ["J", "o", "h", "n"],
            html_template="""
                <h1>Hello, ${value.join('')}!</h1>
                <ul>
                    {{#each value}}
                    <li>{{this}}</li>
                    {{/each}}
                </ul>
            """,
            css_template="""
                h1, li {
                    color: ${color};
                    font-weight: ${bold ? 'bold' : 'normal'};
                }
            """,
            color="green",
            bold=True,
            elem_id="css",
        )
    with gr.Row():
        btn = gr.Button("Update HTML")
        btn_blue = gr.Button("Make HTML Blue")

    def update_templated_html_css(name, color, bold):
        return gr.HTML(value=list(name), color=color, bold=bold)

    btn.click(
        update_templated_html_css,
        inputs=[name2, color, bold],
        outputs=templated_html_css,
    )
    btn_blue.click(lambda: gr.HTML(color="blue"), outputs=templated_html_css)

    gr.Markdown("""
    # JS Prop Updates
    We can now trigger events from gr.HTML using event listeners in `js_on_load`. This script has access to `element` which refers to the parent element, and `trigger(event_name)` or `trigger(event_name, event_data)`, which can be used to dispatch events.
    """)

    button_set = gr.HTML(
        html_template="""
        <button id='A'>A</button>
        <button id='B'>B</button>
        <button id='C'>C</button>
        """,
        css_template="""
        button {
            padding: 10px;
            background-color: red;
        }
        """,
        js_on_load="""
        const buttons = element.querySelectorAll('button');
        buttons.forEach(button => {
            button.addEventListener('click', () => {
                trigger('click', {clicked: button.innerText});
            });
        });
        """,
        elem_id="button_set",
    )
    clicked_box = gr.Textbox(label="Clicked")

    def on_button_click(evt: gr.EventData):
        return evt.clicked

    button_set.click(on_button_click, outputs=clicked_box)

    gr.Markdown("""
    # JS Prop Changes
    You can also update `value` or any other prop of the component from JS using `props`, e.g., `props.value = "new value"` will update the `value` prop and re-render the HTML template.
    """)
    form = gr.HTML(
        html_template="""
        <input type="text" value="${value}" id="text-input" />
        <p>${value.length} letters</p>
        <button class="submit" style="display: ${valid ? 'block' : 'none'};">submit</button>
        <button class="clear">clear</button>
        """,
        js_on_load="""
        const input = element.querySelector('input');
        const submit_button = element.querySelector('button.submit');
        const clear_button = element.querySelector('button.clear');
        input.addEventListener('input', () => {
            props.valid = input.value.length > 5;
            props.value = input.value;
        });
        submit_button.addEventListener('click', () => {
            trigger('submit');
        });
        clear_button.addEventListener('click', () => {
            props.value = "";
            props.valid = false;
            trigger('clear');
        });
    """,
        valid=False,
        elem_id="form",
    )
    output_box = gr.Textbox(label="Output Box")
    form.submit(lambda x: x, form, outputs=output_box)
    output_box.submit(lambda x: x, output_box, outputs=form)

    gr.Markdown("""
    # Watch API
    Use `watch` inside `js_on_load` to run a callback after the template re-renders whenever specific props are changed from the backend (Python event listener). The callback is NOT triggered by frontend (JavaScript) changes to props. The callback takes no arguments — read current values from `props` directly.
    """)
    watch_html = gr.HTML(
        value=0,
        html_template="""
        <div>
            <div>value: ${value}</div>
        </div>
        """,
        js_on_load="""
        watch('value', () => {
            if (props.value >= 3) {
                trigger('submit');
            }
        });
        """,
        elem_id="watch_demo",
    )
    watch_output = gr.Textbox(label="Watch Output")
    watch_inc_btn = gr.Button("Increment")
    watch_inc_btn.click(lambda x: (x or 0) + 1, watch_html, outputs=watch_html)
    watch_html.submit(lambda x: x, watch_html, outputs=watch_output)

    gr.Markdown("""
    # Extending gr.HTML for new Components
    You can create your own Components by extending the gr.HTML class.
    """)

    class ListComponent(gr.HTML):
        def __init__(self, container=True, label="List", ordered=False, **kwargs):
            self.ordered = ordered
            super().__init__(
                html_template="""
                <h2>${label}</h2>
                ${ordered ? `<ol>` : `<ul>`}
                    ${value.map(item => `<li>${item}</li>`).join('')}
                ${ordered ? `</ol>` : `</ul>`}
                """,
                container=container,
                label=label,
                ordered=ordered,
                **kwargs,
            )

    l1 = ListComponent(
        label="Fruits", value=["Apple", "Banana", "Cherry"], elem_id="fruits"
    )
    l2 = ListComponent(
        label="Vegetables",
        value=["Carrot", "Broccoli", "Spinach"],
        elem_id="vegetables",
    )

    make_ordered_btn = gr.Button("Make Ordered")
    make_unordered_btn = gr.Button("Make Unordered")

    make_ordered_btn.click(
        lambda: [ListComponent(ordered=True), ListComponent(ordered=True)],
        outputs=[l1, l2],
    )
    make_unordered_btn.click(
        lambda: [ListComponent(ordered=False), ListComponent(ordered=False)],
        outputs=[l1, l2],
    )

    failed_template = gr.HTML(
        value=None,
        html_template="""
          ${Zalue}
        """,
    )

    gr.Markdown("""
    # File Upload via gr.HTML
    The `upload` async function is available in `js_on_load`. It takes a JavaScript `File` object,
    uploads it to the Gradio server, and returns the server-side file path as a string.
    """)

    upload_html = gr.HTML(
        html_template="""
        <div>
            <input type="file" id="html-file-input" />
            <button id="html-upload-btn" style="margin-left: 8px; padding: 4px 8px;">Upload</button>
            <p id="html-upload-status">No file uploaded yet.</p>
        </div>
        """,
        js_on_load="""
        const input = element.querySelector('#html-file-input');
        const btn = element.querySelector('#html-upload-btn');
        const status = element.querySelector('#html-upload-status');

        btn.addEventListener('click', async () => {
            const file = input.files[0];
            if (!file) {
                status.textContent = 'Please select a file first.';
                return;
            }
            status.textContent = 'Uploading...';
            try {
                const { path, url } = await upload(file);
                status.textContent = 'Uploaded: ' + path;
                trigger('upload', { path: path, url: url, name: file.name });
            } catch (e) {
                status.textContent = 'Upload failed: ' + e.message;
            }
        });
        """,
        elem_id="upload_html"
    )
    upload_result = gr.Textbox(label="Upload Result", elem_id="upload_result")

    def on_html_upload(evt: gr.EventData):
        return evt.path

    upload_html.upload(on_html_upload, outputs=upload_result)

    class TodoList(gr.HTML):
        def __init__(
            self,
            value: list[str] | None = None,
            completed: list[int] | None = None,
            **kwargs,
        ):
            self.completed = completed or []
            super().__init__(
                html_template="""
                <h2>Todo List</h2>
                <ul>
                    ${value.map((item, index) => `
                        <li style="text-decoration: ${completed.includes(index) ? 'line-through' : 'none'};">
                            <input type="checkbox" ${completed.includes(index) ? 'checked' : ''} data-index="${index}" />
                            ${item}
                        </li>
                    `).join('')}
                </ul>
                """,
                js_on_load="""
                const checkboxes = element.querySelectorAll('input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', () => {
                        const index = parseInt(checkbox.getAttribute('data-index'));
                        let completed = props.completed || [];
                        if (checkbox.checked) {
                            if (!completed.includes(index)) {
                                completed.push(index);
                            }
                        } else {
                            completed = completed.filter(i => i !== index);
                        }
                        props.completed = [...completed];
                        console.log(JSON.stringify(props.completed))
                    });
                });
                """,
                completed=self.completed,
                value=value,
                **kwargs,
            )

    todo_list = TodoList(
        value=["Buy groceries", "Walk the dog", "Read a book"],
        completed=[1],
        elem_id="todo",
    )

    gr.Markdown("""
    # HTML Children
    Use `@children` in `html_template` to render child components inside the HTML wrapper.
    """)
    with gr.HTML(
        html_template="""
        <h2>${title}</h2>
        @children
        <button class="send">Send</button>
    """,
        css_template="""
        border: 2px solid gray;
        border-radius: 8px;
        padding: 16px;
    """,
        js_on_load="""
        element.querySelector('.send').addEventListener('click', () => {
            trigger('submit');
        });
    """,
        title="Contact Form",
        elem_id="children_form",
    ) as children_form:
        children_name = gr.Textbox(label="Your Name")
        children_email = gr.Textbox(label="Your Email")

    children_output = gr.Textbox(label="Children Output")
    children_form.submit(
        lambda name, email: f"Name: {name}, Email: {email}",
        inputs=[children_name, children_email],
        outputs=children_output,
    )

    gr.Markdown("""
    # Server Functions
    You can call Python functions from `js_on_load` using the `server` object. Pass a list of functions via `server_functions` and they become available as async methods on the `server` object in your JavaScript code.
    """)

    def list_directory(path):
        try:
            items = sorted(os.listdir(path))
            return [
                {"name": item, "is_dir": os.path.isdir(os.path.join(path, item))}
                for item in items[:20]
            ]
        except (FileNotFoundError, PermissionError):
            return []

    server_fn_html = gr.HTML(
        value=os.path.dirname(__file__),
        html_template="""
            <div>
                <p>Directory: <strong>${value}</strong></p>
                <div id='server-fn-tree'></div>
                <button id='server-fn-load'>Load Files</button>
            </div>
        """,
        js_on_load="""
            const loadBtn = element.querySelector('#server-fn-load');
            const tree = element.querySelector('#server-fn-tree');
            loadBtn.addEventListener('click', async () => {
                tree.innerHTML = '<em>Loading...</em>';
                const items = await server.list_directory(props.value);
                tree.innerHTML = '';
                items.forEach(item => {
                    const el = document.createElement('div');
                    el.textContent = (item.is_dir ? '📁 ' : '📄 ') + item.name;
                    el.className = 'server-fn-item';
                    tree.appendChild(el);
                });
            });
        """,
        css_template="""
            #server-fn-tree { padding: 8px; min-height: 20px; }
            .server-fn-item { padding: 2px 8px; }
            #server-fn-load { padding: 6px 12px; margin-top: 8px; }
        """,
        server_functions=[list_directory],
        elem_id="server_fns",
    )

    gr.Markdown("""
    # Custom Events
    You can trigger custom events (not in the standard event list) from `js_on_load` using `trigger('custom_event_name', data)`. As long as the event name appears in quotes in `js_on_load`, you can attach a Python listener using `component.custom_event_name(fn, ...)`.
    """)

    keyboard = gr.HTML(
        html_template="<p>Press any key...</p>",
        js_on_load="""
        document.addEventListener('keydown', (e) => {
            trigger('keypress', {key: e.key});
        });
        """,
        elem_id="custom_event",
    )

    key_output = gr.Textbox(label="Key Pressed", elem_id="key_output")

    def get_key(evt_data: gr.EventData):
        return evt_data.key

    keyboard.keypress(get_key, None, key_output)

    gr.Markdown("""
    # Head / Third-Party Scripts
    The `head` parameter lets you load third-party JS/CSS libraries directly on the component.
    Scripts are deduplicated by `src`, so multiple components sharing the same library only load it once.
    """)

    head_html = gr.HTML(
        value=[30, 70, 45, 90, 60],
        html_template="""
        <canvas id="head-chart" width="300" height="200"></canvas>
        """,
        js_on_load="""
        const canvas = element.querySelector('#head-chart');
        new Chart(canvas, {
            type: 'bar',
            data: {
                labels: props.value.map((_, i) => 'Item ' + (i + 1)),
                datasets: [{
                    label: 'Values',
                    data: props.value,
                    backgroundColor: 'rgba(99, 132, 255, 0.5)',
                }]
            },
            options: { responsive: false }
        });
        """,
        head='<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>',
        elem_id="head_demo",
    )

if __name__ == "__main__":
    demo.launch()
```

### Event Listeners

#### Description

Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called.

#### Supported Event Listeners

The `HTML` component supports the following event listeners:

- `HTML.change(fn, ...)`: Triggered when the value of the HTML changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.
- `HTML.input(fn, ...)`: This listener is triggered when the user changes the value of the HTML.
- `HTML.click(fn, ...)`: Triggered when the HTML is clicked.
- `HTML.double_click(fn, ...)`: Triggered when the HTML is double clicked.
- `HTML.submit(fn, ...)`: This listener is triggered when the user presses the Enter key while the HTML is focused.
- `HTML.stop(fn, ...)`: This listener is triggered when the user reaches the end of the media playing in the HTML.
- `HTML.edit(fn, ...)`: This listener is triggered when the user edits the HTML (e.g. image) using the built-in editor.
- `HTML.clear(fn, ...)`: This listener is triggered when the user clears the HTML using the clear button for the component.
- `HTML.play(fn, ...)`: This listener is triggered when the user plays the media in the HTML.
- `HTML.pause(fn, ...)`: This listener is triggered when the media in the HTML stops for any reason.
- `HTML.end(fn, ...)`: This listener is triggered when the user reaches the end of the media playing in the HTML.
- `HTML.start_recording(fn, ...)`: This listener is triggered when the user starts recording with the HTML.
- `HTML.pause_recording(fn, ...)`: This listener is triggered when the user pauses recording with the HTML.
- `HTML.stop_recording(fn, ...)`: This listener is triggered when the user stops recording with the HTML.
- `HTML.focus(fn, ...)`: This listener is triggered when the HTML is focused.
- `HTML.blur(fn, ...)`: This listener is triggered when the HTML is unfocused/blurred.
- `HTML.upload(fn, ...)`: This listener is triggered when the user uploads a file into the HTML.
- `HTML.release(fn, ...)`: This listener is triggered when the user releases the mouse on this HTML.
- `HTML.select(fn, ...)`: Event listener for when the user selects or deselects the HTML. Uses event data gradio.SelectData to carry `value` referring to the label of the HTML, and `selected` to refer to state of the HTML. See https://www.gradio.app/main/docs/gradio/eventdata for more details.
- `HTML.stream(fn, ...)`: This listener is triggered when the user streams the HTML.
- `HTML.like(fn, ...)`: This listener is triggered when the user likes/dislikes from within the HTML. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.
- `HTML.example_select(fn, ...)`: This listener is triggered when the user clicks on an example from within the HTML. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.
- `HTML.option_select(fn, ...)`: This listener is triggered when the user clicks on an option from within the HTML. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.
- `HTML.load(fn, ...)`: This listener is triggered when the HTML initially loads in the browser.
- `HTML.key_up(fn, ...)`: This listener is triggered when the user presses a key while the HTML is focused.
- `HTML.apply(fn, ...)`: This listener is triggered when the user applies changes to the HTML through an integrated UI action.
- `HTML.delete(fn, ...)`: This listener is triggered when the user deletes and item from the HTML. Uses event data gradio.DeletedFileData to carry `value` referring to the file that was deleted as an instance of FileData. See EventData documentation on how to use this event data
- `HTML.tick(fn, ...)`: This listener is triggered at regular intervals defined by the HTML.
- `HTML.undo(fn, ...)`: This listener is triggered when the user clicks the undo button in the chatbot message.
- `HTML.retry(fn, ...)`: This listener is triggered when the user clicks the retry button in the chatbot message.
- `HTML.expand(fn, ...)`: This listener is triggered when the HTML is expanded.
- `HTML.collapse(fn, ...)`: This listener is triggered when the HTML is collapsed.
- `HTML.download(fn, ...)`: This listener is triggered when the user downloads a file from the HTML. Uses event data gradio.DownloadData to carry information about the downloaded file as a FileData object. See EventData documentation on how to use this event data
- `HTML.copy(fn, ...)`: This listener is triggered when the user copies content from the HTML. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data

#### Event Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fn` | `Callable \| None \| Literal['decorator']` | `"decorator"` | the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. |
| `inputs` | `Component \| BlockContext \| list[Component \| BlockContext] \| Set[Component \| BlockContext] \| None` | `None` | List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. |
| `outputs` | `Component \| BlockContext \| list[Component \| BlockContext] \| Set[Component \| BlockContext] \| None` | `None` | List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. |
| `api_name` | `str \| None` | `None` | defines how the endpoint appears in the API docs. Can be a string or None. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. |
| `api_description` | `str \| None \| Literal[False]` | `None` | Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. |
| `scroll_to_output` | `bool` | `False` | If True, will scroll to output component on completion |
| `show_progress` | `Literal['full', 'minimal', 'hidden']` | `"full"` | how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all |
| `show_progress_on` | `Component \| list[Component] \| None` | `None` | Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. |
| `queue` | `bool` | `True` | If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. |
| `batch` | `bool` | `False` | If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. |
| `max_batch_size` | `int` | `4` | Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) |
| `preprocess` | `bool` | `True` | If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). |
| `postprocess` | `bool` | `True` | If False, will not run postprocessing of component data before returning 'fn' output to the browser. |
| `cancels` | `dict[str, Any] \| list[dict[str, Any]] \| None` | `None` | A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. |
| `trigger_mode` | `Literal['once', 'multiple', 'always_last'] \| None` | `None` | If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. |
| `js` | `str \| Literal[True] \| None` | `None` | Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. |
| `concurrency_limit` | `int \| None \| Literal['default']` | `"default"` | If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). |
| `concurrency_id` | `str \| None` | `None` | If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. |
| `api_visibility` | `Literal['public', 'private', 'undocumented']` | `"public"` | controls the visibility and accessibility of this endpoint. Can be "public" (shown in API docs and callable by clients), "private" (hidden from API docs and not callable by the Gradio client libraries), or "undocumented" (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to "private". |
| `time_limit` | `int \| None` | `None` |  |
| `stream_every` | `float` | `0.5` |  |
| `key` | `int \| str \| tuple[int \| str, ...] \| None` | `None` | A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. |
| `validator` | `Callable \| None` | `None` | Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value. |
- [Custom HTML Components](https://www.gradio.app/guides/custom-HTML-components/)
- [Custom CSS And JS](https://www.gradio.app/guides/custom-CSS-and-JS/)
