Search code examples
d3.jstooltip

Using div tooltips versus using g tooltips in d3


Say i wanted to add a tooltip to a chart i'm developing, i could use regular html elements like a div or i could use g elements inside the svg itself.

i would like to know what are the main differences between using div tooltips like so:

var tooltip = d3.select('body')
  .append('div')
    .style('position', 'absolute')
    .style('display', 'none');

and then move it around and modify it with

selection.on('someEvent', () => {
    tooltip
        .style('display', null)
        .style('top', mouseY + 'px')
        .style('left', mouseX + 'px')
        ... /* do what needs to be done */
});

or opt for a g element:

var tooltip = d3.select('svg')
  .append('g')
    .style('display', 'none');

and then translate it where needed using the transform attribute

selection.on('someEvent', () => {
    tooltip
        .attr('transform', 'translate(' + mouseX + ',' + mouseY + ')')
        .style('display', null)
        ... /* do what needs to be done */
});

personally i like the g element a little bit more because looks a lot less like a hack, but it can be kind of clunky to manage what is actually in the tooltip. So i'm really confused here guys, any help?


Solution

  • Div

    Pros

    • Content is more flexible and responsive, large texts can be wrapped
    • Tooltip can be showed outside of SVG

    Cons

    • Somewhat is hard to position on desired place

    g

    Pros

    • Positioning is somewhat easy
    • It's content is more solid , than div

    Cons

    • If you have tooltip of large size, part of outside svg will be trimmed
    • Complex tooltip content requires more time