Call javascript from a button click event

You can use triple back-ticks to embed code:

```
this is some code
```

Now, I believe the reason that a bare display doesn’t work is that the comm message isn’t handled by any particular cell, so only the JupyterLab log console receives it. For whatever reason, this does not execute Javascript display objects. You could solve this by using the HTML display object with a <script> tag instead, or use an Output widget:

from IPython.display import HTML, Javascript
button = widgets.Button(
    description='Button',
    disabled=False,
    button_style='',
    tooltip='Button',
    icon='check'
)
        
output = widgets.Output()

@output.capture(clear_output=True)
def on_button_clicked(b):
    my_js = """
    console.log('hello world!');
    """
    display(Javascript(my_js))

button.on_click(on_button_clicked)
display(button, output)
1 Like