Home > Web Front-end > JS Tutorial > body text

How to Access Node Datum on Mouseover in D3 v6?

Patricia Arquette
Release: 2024-10-24 07:23:30
Original
204 people have browsed it

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) { .... })
Copy after login

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) { .... })
Copy after login

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));
  });
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!