D3 was probably sold to you under the banner of interactive visualization! And yet, hiding somewhere in the back of your head, you’re saying to yourself come on dude, we haven’t done a single goddamn interactive thing. So today we’re going to do those goddamn interactive things.
Mouse events
When your mouse does something to an element on the page - hovers over it, clicks it, etc etc etc - these are called mouse events. D3 supports mouse events just the same as it supports everything else!
Clicking on a data point works like this:
And hovering onto a data point works like this:
d is (as always) the data point, and i is (as always) the index of the element you’re looking at.
Not so bad, right? Take a look at the following code, then open up the JS console to see what’s happening as you move your mouse over the circles.
But that stuff’s not so fun, what’s fun is when you can change the element you’re clicking or hovering on.
In order to make a change, you need to use this thing called this. Don’t ask me what it is or anything, just be a good kid and use console.log(this); and look at it.
this in this particular instance is the circle you’re clicking or the rectangle you’re hovering or whatever random element you’re interacting with. As a result, you can use d3 to select is and then change its attributes, just like anything else
Notice how the circles stay red after you stop hovering? That’s because mouseover isn’t exactly the same as what you’d think “hover” means - instead, it’s what should happen when you mouse moves on top of the element. It doesn’t care at all about when you move off.
Of course, another event does - mouseout! Easy enough to remember, right? To do a hover, more or less you need to have mouseover make the hover effect and then have mouseout remove it.
Let’s add a hover effect that goes away when you mouseout the element.