d3 hover over legend, how to determine id

1.5k views Asked by At

I'm trying to determine that when I hover over a certain legend item, how do I know which one I hover over.

// draw legend colored rectangles
legend.append("rect")
    .attr("x", width + 170)
    .attr("width", 18)
    .attr("height", 18)
    .on("mouseover", function(d) {
    })
    .style("fill", color);

Right now, there are 3 rects in the legend. How do I get the id of the rect that I hover over?

1

There are 1 answers

1
meetamit On BEST ANSWER

Inside the mouseover handler, this is the DOM element that triggered the event. So you can do something like

.on("mouseover", function(d) {
    d3.select(this).attr('id');// presumes that <rect> has an id!
})

To assign id to rect, you call .attr('id', 'some_id') on it.

But if you're at a stage where you don't already have ids on the rects (despite what you titled your post), then consider using d3's data binding and the enter, update, (exit) selections in order to create your legend, and use d in the "mouseover" function to determine which legend element is being interacted with (instead of using ids on the DOM element).