software_writer
software_writer

Reputation: 4458

Parameters needed for d3.mouse()

I am trying to get mouse coordinates relative to a group element. Here's the code:

var backRect = chart.append("g").attr("class", "rect");
var g = backRect.append('rect')
        .style('stroke', 'none')
        .style('fill', '#FFF')
        .style('fill-opacity', 0)
        .attr({
            width: width,
            height: height,
            'pointer-events': 'none',
            'class': 'backRect'
        });

// the code below is inside another container's event; but I want mouse coordinates relative to the above rect, hence can't use d3.mouse(this)
// get mouse pointer location
        var coordinates = [0, 0];
        coordinates = d3.mouse(backRect); // d3.select(".rect") does not work either

but get the following error:

d3.min.js:1 Uncaught TypeError: n.getBoundingClientRect is not a function

According to the d3 mouse docs d3.mouse() takes a container which can be svg or g element.

What parameter should I pass to d3.mouse()? I tried d3.select(".rect") which is not working either.

Upvotes: 4

Views: 3948

Answers (2)

software_writer
software_writer

Reputation: 4458

Using d3.mouse(backRect.node()) did the trick.

Upvotes: 8

Sundeep
Sundeep

Reputation: 1606

You should be using d3.mouse() inside an event to get the values relative to the passed container.

Check this block

http://bl.ocks.org/hlucasfranca/f133da4493553963e710

svg.on("click", function() {
          var coords = d3.mouse(this);
          ........
          ........
})

Upvotes: 0

Related Questions