4

I want to listen to keyboard event in plotlyjs(spacebar key pressed to be more specific). When spacebar is pressed I want to discontinue line drawing on mouse click.

I have added eventListener to listen to key events but does not seem to work. Is there any specific way to capture keyboard events.

plotCon.addEventListener('click', function(e){
      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, config, {displayModeBar: false});
    });

    plotCon.addEventListener('keydown', function(e) {
      if(e.key == " " || e.code == "Space" || e.keyCode == 32) {
        alert('key pressed');
      }
    });
Derek O
  • 16,770
  • 4
  • 24
  • 43

1 Answers1

0

For the click-to-start event, use Plotly's built-in method. Plotly has its own key events, so it will remove any event you task to the Plotly-specific div tag. You can set the key event to the document or a container, though.

I've added alerts, so you see when you've moved in and out of drawing mode.

plotlyDiv = document.getElementById('myDiv');

var data = [trace1 = {
  x: [1, 2, 3, 4, 2, 3, 4, 5],
  y: [10, 15, 13, 17, 16, 5, 11, 10],
  mode: 'markers',
  marker: {
    size: 20,
    color: 'red'
  }
}];

var layout = {
  dragmode: 'zoom'
};

var options = {
  displayModeBar: true
}

Plotly.newPlot('myDiv', data, layout, options);

plotlyDiv.on('plotly_click', function(event) {
  Plotly.relayout('myDiv', 'dragmode', 'drawopenpath');
  alert('You are drawing now');
});

document.addEventListener('keyup', function(event) {
  if (event.which == 32 || event.keyCode == 32) {
    Plotly.relayout('myDiv', 'dragmode', 'zoom');
    alert('Drawing mode has ended')
  }
});
<head>
  <!-- Plotly.js -->
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>

<body>
  <div id="myDiv" style="width: 600px; height: 500px;">
    <!-- Plotly chart will be drawn inside this DIV -->
  </div>
</body>
Kat
  • 15,669
  • 3
  • 18
  • 51