Home >Web Front-end >JS Tutorial >How to Access Node Datum on Mouseover in D3 v6?
Unable to Get Node Datum on Mouseover in D3 v6
Problem:
In D3 v6, when using selection.on() to add a mouseover event listener to nodes, the event data is returned instead of the datum of the node. How can the datum be obtained?
Answer:
D3v5 and Earlier:
In D3 v5 and earlier, the following pattern was used to define an event listener:
selection.on("eventType", function(d, i, nodes) { .... })
Where d is the datum of the element triggering the event, i is its index, and nodes is the current group of elements. Event information could be accessed with d3.event.
D3v6:
In D3 v6, the event listener pattern has changed to:
selection.on("eventType", function(event, d) { .... })
Now, the event is passed directly as the first parameter to the listener, while the datum is the second parameter. d3.event has been removed.
Using d3.select(this)
In the event listener function, d3.select(this) can still be used to select the triggering element, even in D3 v6. However, when using arrow functions, this will have a different scope.
Positioning:
To obtain the x,y position of the event, which was previously retrieved with d3.mouse(this), you can now use d3.pointer(event). To access the x and y properties directly, use event.x and event.y instead of d3.event.x and d3.event.y.
Example:
The following example shows how to pass the event and datum to an event listener function in D3 v6:
const svg = d3 .select("body") .append("svg"); svg .selectAll("rect") .data([1, 2, 3]) .enter() .append("rect") .attr("width", 30) .attr("height", 30) .attr("x", function (d) { return d * 50; }) .on("click", function (event, d) { console.log(d); console.log(d3.pointer(event)); });
The above is the detailed content of How to Access Node Datum on Mouseover in D3 v6?. For more information, please follow other related articles on the PHP Chinese website!