score:5

Accepted answer

you have to use d3.event.keycode. according to the api, d3.event...:

... is set during the invocation of an event listener, and is reset after the listener terminates. use this to access standard event fields.

here is a basic demo. click on "foo", "bar" or "baz" to focus, then press any key and look at the console:

var body = d3.select("body");
var p = body.selectall(null)
  .data(["foo", "bar", "baz"])
  .enter()
  .append("p")
  .attr('tabindex', '0')
  .attr('focusable', 'true')
  .html(string)
  .on("keypress", function() {
    if(d3.event.keycode === 32 || d3.event.keycode === 13){
    console.log("congrats, you pressed enter or space!")
    }
  })
<script src="https://d3js.org/d3.v4.min.js"></script>


Related Query