smcs
smcs

Reputation: 2004

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);
            })

Upvotes: 5

Views: 5175

Answers (2)

Guenter
Guenter

Reputation: 485

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
  })

Upvotes: 1

Chirag Kothari
Chirag Kothari

Reputation: 1410

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);
      })

Upvotes: 3

Related Questions