How to trigger js function from click event


I am new to bokeh and bokehjs. Currently for a project, I have a plot made in javascript using the low-level scatterplot model example from bokeh docs (Developing with JavaScript — Bokeh 2.4.1 Documentation). However, I would like to add a click event when clicking on a scatterplot point that triggers a js function. In the python bokeh, you can attach callbacks and use js_on_event or even use on_click, but how would I achieve that functionality only in js (i get a function not found error when using those methods)?

For this I generally use the ‘selection’ functionality bokeh offers. Essentially you allow the user to select renderers that are driven by a columndatasource, then you trigger a callback whenever the selected indices change. The real benefit of this setup is that not only can you get at one selected data point at a time, you can use certain tools to “collect” multiple selected data points at once e.g. lasso_select, and then perform some aggregation on that user-defined selection. I’m not doing that in this example, but I hope you see the power of that :slight_smile:

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, CustomJS, Scatter

data = {'x':[1,2,3,4,5],'y':[2,4,6,7,9],'fruit':['banana','orange','apple','grape','blueberry'],'color':['yellow','orange','red','purple','blue']}
src = ColumnDataSource(data=data)
f = figure(tools=['tap','lasso_select'])
sc = Scatter(x='x',y='y',fill_color='color',size=10)
sc_hvr = Scatter(x='x',y='y',fill_color='color',size=10)
sc_rend = f.add_glyph(src,sc,hover_glyph=sc_hvr)

cb = CustomJS(args=dict(src=src)
              var sel_inds = src.selected.indices
              console.log("Here's what is in this selection")
              for (var i=0;i<sel_inds.length;i++){
                      var sel_i = sel_inds[i]


Hope this helps!

Correct me if I am wrong, but your example was done in python, correct? Is there a way to do that same functionality only in javascript?

Ah. Yes. Sorry, I just reread your post and I now understand you’re building in bokehjs. My example is “basic python with CustomJS code getting triggered” so this example snipper is not what you need.

But I’d bet that the approach to take is still using the “selection” functionality, and triggering a callback when the selected indices change. How to actually do that in bokehjs from scratch, I can’t help.

Thanks for trying to help! At least once I understand how bokehjs CustomJS works, I can come back and implement your example.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.