Search code examples
bokeh

js_on_event on Div widget in bokeh


Is it possible to use js_on_event for Div widgets? I would ultimately like to trigger a callback in python whenever an event is triggered on a Div widget (tap, press, mouse enter, mouse leave, etc), and I suppose going through js_on_event is the way to do that(?). Anyways, I have tried the following:

from bokeh import events
from bokeh.layouts import layout
from bokeh.models import CustomJS, Div

from lib.bokeh.util.bokeh_util import display

div = Div(style={'background': 'gray', 'min-width': '500px', 'min-height': '500px'})

div.js_on_event(events.Tap, CustomJS(code="""
    console.log("Does this work?")
    """))

display(layout(div, sizing_mode='stretch_both'))

But this does not seem to have any effect.

display is a convenience function that fires up a bokeh Server.


Solution

  • To trigger Python callbacks, you'd need on_event. js_on_event is for triggering JS code in browser, without any communication with the server.

    But either way, the Tap event works only on instances of Plot - it doesn't work on any other model, even if it has a visual representation.

    There are two ways to solve your problem. If you just need something simple like the Tap event, you can (and probably should) use the regular Button. But if you need something more complicated, you can create a custom Bokeh model that would process any JS events, convert them to Bokeh events, and send them to the server.