How to add/track keyboard events in plotlyjs

I have requirement where in if I press on spacebar it should stop drawing lines on plotly on successive mouse clicks. I have added eventListener for keyup however its not working, but it works for click events. I have tried searching in the documentation but was not able to find any apt solution. Any insights would be helpful. I have pasted the code snippet below

Plotly.newPlot(‘plotlyContainer’, data, layout, {displayModeBar: false}).then(clickEv);

function clickEv() {
var xaxis = plotCon._fullLayout.xaxis;
var yaxis = plotCon._fullLayout.yaxis;
var l = plotCon._fullLayout.margin.l;
var t = plotCon._fullLayout.margin.t;

plotCon.addEventListener('click', function(e){
  // data[0].x.push(xaxis.p2c(e.x - l));
  // data[0].y.push(yaxis.p2c(e.y - t));      
  var clickCor = e.target.getBoundingClientRect();      
  data[0].x.push(plotCon._fullLayout.xaxis.p2d(e.clientX - clickCor.left));
  data[0].y.push(plotCon._fullLayout.yaxis.p2d(e.clientY - clickCor.top));
  image1Cor.concat(data[0].x, data[0].y);
  Plotly.update(plotCon, data, layout, {displayModeBar: false});
});

plotCon.addEventListener('keydown', function(event) {
  if(event.key == " " || event.code == "Space" || event.keyCode == 32) {
    alert('key pressed');
  }
});

}

Hello @vinodh,

I think for keydown/keyup to work, it would have to be active somehow… You could use the click event to set a variable, and then when you hit space, if that variable is true, it does something. :slight_smile:

You’d have to add the listener to document.

Hi @jinnyzor, thanks for the solution. Yes I have added listener to the document for keyup event.

1 Like

Just confirming, this is indeed working now?

Hi @jinnyzor, variable approach didnt work, for now I have added listener for entire document and its working.

1 Like