How to highlight features on mouseover?

时间:2019-04-17 01:08:22

标签: javascript d3.js

I am making a map using D3 and am trying to add some dynamic highlighting to it. Ex., when you mouseover certain features, the border changes color/weight. I'm using the following code to try to accomplish this:

function setEnumerationUnits(manhattan, map, path, colorScale){

    //add Manhattan NTAs to map
    var manhattan = map.selectAll(".manhattan")
        .data(manhattan)
        .enter()
        .append("path")
        .attr("class", function(d){
            return "manhattan " + d.properties.ntacode;
        })
        .attr("d", path)
        .style("fill", function(d){
            return choropleth(d.properties, colorScale);
        })
        .on("mouseover", function(d){
            highlight(d.properties);
        });

    //add style descriptor to each path
    var desc = manhattan.append("desc")
        .text('{"stroke": "#000", "stroke-width": "0.5px"}');
};

. . .

//function to highlight enumeration units and bars
function highlight(props){
    //change stroke
    var selected = d3.selectAll("." + props.ntaname)
        .style({
            "stroke": "blue",
            "stroke-width": "2"
        });
    setLabel(props);
};

I'm expecting to see features being outlined when I "brush" over them, but no luck. When I look at the console, I get type errors saying, "cannot read property 'style' of null" and "cannot read property 'html' of null". How can I change this so that the highlight shows up?

1 个答案:

答案 0 :(得分:0)

You have to pass the whole datum to the highlight function, not only a single property.

So, instead of:

  .on("mouseover", function(d){
      highlight(d.properties);
  });

It should be:

  .on("mouseover", function(d){
      highlight(d);
  });

Or even shorter:

  .on("mouseover", highlight);

Finally, since you didn't share the setLabel function, I don't know if it requires a property or the whole datum. Therefore, you have to change that accordingly.