Updating Marker on Click

I’m using Bokeh version 2.4.3. Unfortunately, because of other dependencies, I can’t upgrade.

I have a marker on a plot and I would like to add a feature where the user can move the marker on the plot with a click/tap. I want to use the cb_obj.x to make the update, but I’m not sure how to get it out of the CustomJS code. Here is my code:

from bokeh.plotting import figure, curdoc, show
from bokeh.models.callbacks import CustomJS


x = list(range(1,10))
y = list(1 for i in range(1,10)) 

p = figure(
    height=130,
    width=1800)
p.line(x=x, y=y)


star_location= 1

r= p.scatter(x= star_location, y= 1, marker='star', size = 15, color = 'red')
   

callback = CustomJS(code="""
    console.log(cb_obj.x)
    r.glyph.x = cb_obj.x
""")


p.js_on_event('tap', callback)


show(p)

Hi Stefeni,

You were nearly there. In the JavaScript callback you want to use r, but that is a Python variable that is not available by default in the JavaScript callback. You have to tell the CustomJS about r by passing in args as well as code. Here is the full working example:

from bokeh.plotting import figure, show
from bokeh.models.callbacks import CustomJS

x = list(range(1,10))
y = list(1 for i in range(1,10))

p = figure(height=130, width=1800)
p.line(x=x, y=y)

star_location= 1
r = p.scatter(x=star_location, y=1, marker='star', size=15, color='red')

callback = CustomJS(args=dict(r=r), code="""
    console.log(cb_obj.x)
    r.glyph.x = cb_obj.x
""")

p.js_on_event('tap', callback)

show(p)
1 Like

That works. Thank you!