Home > Web Front-end > JS Tutorial > How to Grab Node Datum During Mouseover Events in D3 v6?

How to Grab Node Datum During Mouseover Events in D3 v6?

Susan Sarandon
Release: 2024-10-24 07:46:01
Original
646 people have browsed it

How to Grab Node Datum During Mouseover Events in D3 v6?

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

where:

  • d is the event-triggering element's datum
  • i is its index
  • nodes is the current group of selected elements

Event-related data could be accessed using d3.event.

D3v6

With D3v6, the pattern has changed to:

selection.on("eventType", function(event, d) { .... })
Copy after login

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

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

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

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!

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