Add event listener to canvas

I’m trying (and failing miserably) to add an event listener to the chart canvas in this notebook: Countries Selector Input / stuwilmur / Observable.

I am very rusty with observable and the canvas, so if anyone could get me started with any old listener (e.g. console.log on mouse move event) I’d be very grateful!

maybe try: chart.addEventListener('mousemove',e => console.log(e))

Thank you so much @Fil! I seem to have tried everything but this :man_facepalming:.

1 Like

If you want to inspect your event values directly, you can use the Generators.observe helper from Observable’s Standard Library. Add a cell with the following content:

Generators.observe(change => {
  const handler = e => {
    change({x: e.clientX, y: e.clientY});
  };

  chart.addEventListener('mousemove', handler);
  return () => chart.removeEventListener('mousemove', handler);
})

Once you move the mouse over the chart you’ll see the current offset appear as the cell’s value:
image

Thanks this is really helpful.