Events
Listening for events
Events are the backbone to interaction. Something happens, your visualization reacts. This is called listening for an event.
To listen for an event in d3, pull some element(s) with select
or selectAll
, then use .on
to listen for a specific event.
.on('eventname', function() {
// react to the event
})
For example, you might create a bunch of circles, then listen for a click
event.
d3.selectAll("circle")
.data(datapoints)
.enter().append("circle")
.on('click', function(d) {
console.log('got clicked');
console.log(d);
})
You might also have a button on the page, and listen for it to be clicked.
d3.select("#some-button")
.on('click', function() {
console.log('got clicked');
// no data
})
Event names
You can find a full list of events over at Mozilla, but you’ll spend most of your time with the following.
Name | Used for |
click |
Clicking buttons or SVG elements |
mouseover |
A mouse moving over an element |
mouseout |
A mouse moving off of an element |
input |
Typing in an input field |
change |
A checkbox/dropdown/etc was changed. Can also be used with text fields, but input is more inconvenient. |
Note that hover
is not an event. It’s a combination of mouseover
to set the “hovered” state, then mouseout
to set it back to the original state.