Home > Mobile >  How to have an entity trigger a different entities mouseover event (D3)
How to have an entity trigger a different entities mouseover event (D3)

Time:11-05

I currently am working on a GeoJSON of the United States with a mouseover event on every state (for example, one thing that occurs is that it changes the border of the states to bright red to show which one is being highlighted).

Some states are fairly small, especially in New England. I was trying to think of a way to get around this and decided to implement additional buttons on the side that would have the same mouseover event tied to specific states that I have deemed were small.

My question is: how would I go about getting something like highlighting the states borders to happen when mousing over the additional buttons.

My current implementation of the original states themselves is below (I haven't begun work on the additional buttons):

.on("mouseover", function(d) { 
              d3.select(event.target).attr("stroke", "red").attr("stroke-width", "3");
              displayData(d); })
.on("mouseout", function(d) { 
              d3.select(event.target).attr("stroke", "black").attr("stroke-width", "1");
              hideData(d); });

displayData(d) and hideData(d) are used for a tooltip's display. As you can see, the way the mouseover works right now is by capturing the event.target. How would I replicate this for a separate button? Is it possible to somehow tie that button's event.target to the corresponding state?

CodePudding user response:

Just use selection.dispatch, which:

Dispatches a custom event of the specified type to each selected element, in order.

Here is a basic example, hovering over the circles will call a given function. Click on the button to dispatch a "mouseover" to the second circle.

Show code snippet

const svg = d3.select("svg");
const circles = svg.selectAll(null)
  .data(["foo", "bar", "baz"])
  .enter()
  .append("circle")
  .attr("id", (_, i) => `id${i}`)
  .attr("cy", 70)
  .attr("cx", (_, i) => 30   100 * i)
  .attr("r", 30)
  .style("fill", "teal")
  .on("mouseover", (event, d) => {
    console.log(`My name is ${d}`);
  });
d3.select("button").on("click", () => d3.select("#id1").dispatch("mouseover"));
.as-console-wrapper { max-height: 15% !important;}
<script src="https://d3js.org/d3.v7.min.js"></script>
<button>Click me</button>
<svg></svg>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related