Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.on("mouseover") event does not work with nested SVG elements

I have a nested set of elements (SVG). The root element is the graph, and the children are elements in the graph (lines, axis, etc.). Simplified example:

<g transform="translate(80,10)" id="mainGraph">
    <g class="Line">
        <path d="....."></path>
    </g>
</g>

My problem is that if I bind a mouseover/mousemove event (with D3.on("mouseover") for example) to the mainGraph element, it only triggers if I move the mouse over one of the child elements.

One of the things I read is that there is priority of later elements, so I added .style("pointer-events","none") to all child elements, but that didn't work.

like image 448
user2279929 Avatar asked Jul 05 '13 18:07

user2279929


2 Answers

One approach is to add a rectangle filling the whole surface as the first element to catch mouse events that are not caught by elements added later:

something.append('svg:rect')
  .attr('width', width) // the whole width of g/svg
  .attr('height', height) // the whole heigh of g/svg
  .attr('fill', 'none')
  .attr('pointer-events', 'all')
  .on('mouseover', function() {
      // do something
    }     
  });

I believe the <g> element (mainGraph in your example) is just a container, not an actual shape that can receive mouse events.

You might be able to add the mouse event listener on the svg element itself, but I don't think the <g> will work.

like image 174
explunit Avatar answered Oct 02 '22 18:10

explunit


Apart from using a rect element, it should have a CSS property set like this pointer-events: all; for the events to be triggered.

like image 27
Ketan Avatar answered Oct 02 '22 18:10

Ketan