In D3 v6, How to Acquire Node Datum During Mouseover Events
In D3 v6 and later, retrieving a node's bound datum with selection.on() differs from previous versions. Instead of receiving the mouse event data, the datum becomes the second parameter passed to the event listener.
D3v5 and Earlier
Previously, event listeners in D3 followed the pattern:
selection.on("eventType", function(d, i, nodes) { .... })
where:
Event-related data could be accessed using d3.event.
D3v6
With D3v6, the pattern has changed to:
selection.on("eventType", function(event, d) { .... })
Now, the event object is directly passed as the first parameter, while the datum is the second parameter. d3.event has been deprecated as a result.
Accessing the Datum
To retrieve the datum of the mouseover target:
node.on("mouseover", (event, d) => { console.log(d); });
Determining Event Position
In D3v5, you could use d3.mouse(this) to obtain the event's x,y position. In D3v6, use:
d3.pointer(event);
Example
The following example demonstrates obtaining the datum and event position during a mouseover event:
const data = [ { "id": "Myriel", "group": 1 }, { "id": "Napoleon", "group": 1 } ]; const nodes = svg.append("g") .selectAll("circle") .data(data) .join("circle") ...; node.on("mouseover", (event, d) => { console.log(d.id); console.log(d3.pointer(event)); });
The above is the detailed content of How to Grab Node Datum During Mouseover Events in D3 v6?. For more information, please follow other related articles on the PHP Chinese website!