d3 - trigger mouseover event

2019-04-19 01:21发布

I have a map of the US states and counties in a SVG graphic rendered by D3. Each path have mouseover, mouseout and click events bound to it, as well as the FIPS county code set as the path ID.

I have a jQuery Autocomplete input where the user can input the name of a state or county. Given that input, which makes the corresponding FIPS ID available, how can I trigger the mouseover event programatically?

4条回答
做自己的国王
2楼-- · 2019-04-19 01:58

Steve Greatrex's solution worked for me until iOS 9, but not on iOS 10.

After debugging my code and some research it seems the issue was that the createEvent and initEvent functions are deprecated as per this documentation.

The new way of writing this is:

var event = new MouseEvent('SVGEvents', {});
element.dispatchEvent(event);

More explanation about the new way of creating and triggering events with event constructors can be found here.

查看更多
迷人小祖宗
3楼-- · 2019-04-19 02:08

You can achieve this by directly dispatching the event on the desired element:

var event = document.createEvent('SVGEvents');
event.initEvent(eventName,true,true);
element.dispatchEvent(event);

See more detail in this blog post

查看更多
来,给爷笑一个
4楼-- · 2019-04-19 02:13

Structure your javascript such that the the mouseover event calls a javascript function and then you can call that same function any time you want.

查看更多
老娘就宠你
5楼-- · 2019-04-19 02:20

I figured out the answer. The main problem is D3 does not have an explicit trigger function as jQuery does. However, you can simulate it.

Say you have a D3 path built via

d3.json("us-counties.json", function(json){

  thisObj._svg.selectAll("path")
    .data(json.features)
    .enter().append("path")
    .attr("d", thisObj._path)
    .attr("class", "states")
    .attr("id", function(d){
      return d.id; //<-- Sets the ID of this county to the path
    })
    .style("fill", "gray")
    .style("stroke", "black")
    .style("stroke-width", "0.5px")
    .on("dblclick", mapZoom)
    .on("mouseover", mapMouseOver)
    .on("mouseout", mapMouseOut);
});

and a mouseover event handler that changes the fill and stroke colors

var mapMouseOver(d){

  d3.selectAll($("#" + d.id))
    .style("fill", "red")
    .style("stroke", "blue");

}

Typically, most tutorials say to use

d3.select(this)...

but actually using the value works as well. If you have an event handler that gets you the ID of the node, and trigger it via

$("#someDropdownSelect").change(someEventHandler)

function someEventHandler(){

  //get node ID value, sample
  var key = $(this)
              .children(":selected")
              .val();

  //trigger mouseover event handler
  mapMouseOver({id : key});

}

will execute the mouseover event based on a dropdown selection

查看更多
登录 后发表回答