Cannot get D3 .on('mouseover', ...) to work
Asked Answered
K

1

7

I'm learning D3 and I'm trying to display data infomation on a scatterplot by hovering on the SVG circles. I take the data from a csv file (data is on the Solar System, with planet names, masses and radiuses) and all the circles show up correctly but when I try to console.log the data information (for instance the mass) on mouseover it does not log anything. The mouseover action is functioning OK but the console tells me that the value requested is "undefined". Where did I mess up? This is my code:

<!DOCTYPE html>
<html lang="en">
<head>

    <style type="text/css">
    body{
        background-color: black;
    }
    #chart{
        background-color: black;
        width: 800px;
        height: 500px;
        border: solid 1px white;
    }
    svg{
        background-color: white;
    }
    .dot{
        stroke: red;
        stroke-width: 1px;
    }
    </style>
    
    <script type="text/javascript" src="https://d3js.org/d3.v6.min.js"></script>
</head>

<body>

    <div id="chart"></div>

    <script type="text/javascript">
        var width = 800;
        var height = 500;
        var circles;
        var svg = d3.select('#chart')
                .append('svg')
                .attr('width', width + 'px')
                .attr('height', height + 'px');

        d3.csv('astro.csv').then(function(data){

            xScale = d3.scaleLinear()
                .domain([0,500])
                .range([0, 800]);

            circles = svg.selectAll('.dot')
                .data(data)
                .enter()   
                .append('circle')
                .attr('class', '.dot')
                .attr('cx', function(d){
                    return xScale(d.mass);
                })
                .attr('cy', 100)
                .attr('r', 20)
                .on('mouseover', function(d){
                    console.log(d.mass);
                })                
        });
    </script>
</body>
</html>
Kimmie answered 22/4, 2021 at 7:9 Comment(0)
K
14

Since D3 V6, all mouse event handlers has an event passed as the first argument and data as the second. In the V5 or earlier, your code will work.

V6 or higher:

.on('mouseover', (event, d) => console.log(d.mass));

V5 or earlier:

.on('mouseover', d => console.log(d.mass));
Kasten answered 22/4, 2021 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.