How to properly add and use D3 Events?

This question is similar to the one you posted in the d3-js Google Group. Without duplicating what I wrote there, I would reiterate that you probably don’t want d3.dispatch; that is intended for custom event abstractions (such as brushes and behaviors). It’ll be simpler to use native events.

If you want your legend to change the color of the corresponding bar on mouseover, then breakdown the problem into steps:

  1. Detect mouseover on the legend.
  2. Select the corresponding bar.
  3. Change the bar’s fill color.

First, use selection.on to listen for “mouseover” events on the legend elements. Your listener function will be called when the mouse goes over a legend element, and will be called with two arguments: the data (d) and the index (i). You can use this information to select the corresponding bar via d3.select. Lastly, use selection.style to change the “fill” style with the new color.

If you’re not sure how to select the corresponding bar on legend mouseover, there are typically several options. The most straightforward is to select by index, assuming that the number of legend elements and number of rect elements are the same, and they are in the same order. In that case, if a local variable rect contains the rect elements, you could say:

function mouseover(d, i) {
  d3.select(rect[0][i]).style("fill", "red");
}

If you don’t want to rely on index, another option is to scan for the matching bar based on identical data. This uses selection.filter:

function mouseover(d, i) {
  rect.filter(function(p) { return d === p; }).style("fill", "red");
}

Yet another option is to give each rect a unique ID, and then select by id. For example, on initialization, you could say:

rect.attr("id", function(d, i) { return "rect-" + i; });

Then, you could select the rect by id on mouseover:

function mouseover(d, i) {
  d3.select("#rect-" + i).style("fill", "red");
}

The above example is contrived since I used the index to generate the id attribute (in which case, it’s simpler and faster to use the first technique of selecting by index). A more realistic example would be if your data had a name property; you could then use d.name to generate the id attribute, and likewise select by id. You could also select by other attributes or class, if you don’t want to generate a unique id.

Leave a Comment