How to use event handlers in D3.js

Preview image

Today's tip is short and sweet. Event handlers in D3 are about 95% straightforward. Most of the time your code looks like this and you're good to go.

The 5% wrinkle comes in if you need to access the native browser event. As you can see in the code above, the callback we pass to the on method uses the standard D3 function signature. The parameters it takes, in order, are the element's corresponding datum, the element's index in the selection, and the raw nodes that make up the selection.

Notice anything missing from that list?

Yep, the event itself.

Since it's not getting passed into our handler, we need another way to access the event. The way D3 chose to solve this is that, for the duration of your handler function, d3.event will hold a reference to the native event that triggered your listener.

It sounds and feels a little strange, but it works in practice when you need it. Which tends to be rarely, but I digress.

Ch-check it out

I've updated an existing bubble chart example and added some frivolous roll over behaviors. We'll look at one of the handlers here, but definitely check out the whole thing here. The new/relevant code is at the end, and called out by a block comment.

Simply to demonstrate the process, we're going to display the mouse coordinates in our bubbles when they're rolled over. For context, our bubble chart was constructed by nesting a circle element and a text element under a parent g element for each item in our data. As a result, our selection refers to a group of g elements and we have to fetch the individual pieces from within them.

That's it! Kinda weird, but definitely not hard.

Happy hacking!