Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js mouseover fails to trigger with an overlapping object

Tags:

d3.js

In D3.js it seems that objects that are drawn before other objects that then obscure them become invisible to the mouseover listener. Is there a workaround to this?

See this working example.

<!DOCTYPE html>
<meta charset="utf-8">
<head>
    <script type="text/javascript" src="scripts/d3.v3.js"></script>
</head>
<body>
    <div id="viz"></div>
    <script type="text/javascript">

    d3.select("body").style("background-color", "black");

    var sampleSVG = d3.select("#viz")
        .append("svg")
        .attr("width", 400)
        .attr("height", 200);

    sampleSVG.append("circle")
        .style("fill", "grey")
        .style("stroke-width", 2)
        .attr("r", 60)
        .attr("cx", 150)
        .attr("cy", 100)
        .on("mouseover", function(){d3.select(this).style("fill", "red");})
        .on("mouseout", function(){d3.select(this).style("fill", "grey");});

    sampleSVG.append("circle")
        .style("stroke", "yellow")
        .style("opacity", 0.5)
        .style("stroke-width", 2)
        .attr("r", 100)
        .attr("cx", 250)
        .attr("cy", 100)

    </script>
</body>
</html>
like image 204
geotheory Avatar asked Mar 21 '13 18:03

geotheory


1 Answers

The solution is to add ".style("pointer-events", "none");" for the last circle:

sampleSVG.append("circle")
    .style("stroke", "yellow")
    .style("opacity", 0.5)
    .style("stroke-width", 2)
    .attr("r", 100)
    .attr("cx", 250)
    .attr("cy", 100)
    .style("pointer-events", "none");

Here is a working example http://tributary.io/inlet/5215694

Note: If the larger circle has its fill attribute set to 'none', then the example also works as expected without needing the "pointer-events" set to none.

like image 168
RobinL Avatar answered Oct 13 '22 06:10

RobinL