Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing D3 tooltip in cursor location

I'm using d3-tip in my visualisation. I now want to add tooltips to elements that are very wide and may extend out of the visible canvas. By default, the tooltip is shown in the horizontal center of an object, which means in my case that the tooltip might not be in the visible area. What I need is the tooltip showing up in the horizontal position of the cursor but I don't know how to change the tooltip position correctly. I can set an offset and I can get the coordinates of the cursor, but what I can't get is the initial position of the tooltip so that I can compute the right offset. Nor can I set an absolute position:

            .on("mouseover",function(d){
                var coordinates = [0, 0];
                coordinates = d3.mouse(this);
                var x = coordinates[0];
                var y = coordinates[1];
                tip.offset([-20,20]); // this works
                tip.attr("x",40); // this doesn't
                tip.show(d);
            })
like image 907
smcs Avatar asked Sep 07 '16 06:09

smcs


2 Answers

If you want to use offset, you can get the initial position of the tooltip after tip.show(d):

tip.style('top');
tip.style('left');

Similarly, to set the absolute position:

.on('mouseover', function(d){
        var x = d3.event.x,
            y = d3.event.y;

        tip.show(d);

        tip.style('top', y);
        tip.style('left', x);
      })
like image 153
Chirag Kothari Avatar answered Nov 01 '22 10:11

Chirag Kothari


The previously stated answer did not work for me (and cannot be modified as "suggested edit queue is full.."), but with some minor adjustments, it is working fine:

.on('mouseover', function(d){
    var x = d3.event.x,
        y = d3.event.y;

    tip.show(d);

    tip.style('top', y-10 + 'px'); // edited
    tip.style('left', x+'px'); // edited
  })
like image 29
Guenter Avatar answered Nov 01 '22 10:11

Guenter