I have read many posts and answers, but they all seem to be out of date.
My goal is to be able to "tab" through text and run a function on enter and/or spacebar. I have tried keyCode
, charCode
, key
, which
, keypress
, keyup
, keydown
etc...
I have a text node that I can tab through using:
.attr('role', 'button')
.attr('tabindex', '0')
.attr('focusable', 'true')
.on('click', sel)
.on('keypress', function(){if(key == 13 || key == 32){return sel}})
The on click is perfect and the tab works, just the function is not called when the space and enter are used.
any help is appreciated.
I have read many posts and answers, but they all seem to be out of date.
My goal is to be able to "tab" through text and run a function on enter and/or spacebar. I have tried keyCode
, charCode
, key
, which
, keypress
, keyup
, keydown
etc...
I have a text node that I can tab through using:
.attr('role', 'button')
.attr('tabindex', '0')
.attr('focusable', 'true')
.on('click', sel)
.on('keypress', function(){if(key == 13 || key == 32){return sel}})
The on click is perfect and the tab works, just the function is not called when the space and enter are used.
any help is appreciated.
Share Improve this question edited Oct 13, 2017 at 1:04 Gerardo Furtado 102k9 gold badges128 silver badges177 bronze badges asked Oct 12, 2017 at 15:18 BradBrad 871 silver badge6 bronze badges1 Answer
Reset to default 5You 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/d3.v4.min.js"></script>