Customize Tooltip in D3 Charts

Posted on by By Nikhilesh, in Miscellaneous | 0

Customize Tooltip in D3 Charts

Simplest way to customize your tooltip in d3 charts. To achieve a customize tooltip you need to follow these simple steps.

Step 1: First, think what you can show in tooltip. I have created pie chart using d3 charts.In my case I am showing a total votes of my candidate. So I have created one div tag as given below.

Note: Your element id should be uniqe for the element.

<div id="mytooltip" class="hidden">
  <p><strong>Total Votes:</strong></p>
  <p><span id="value">100</span></p>
</div>

Step 2: Style your div tag as per requirement. I have crearted style sheet like that.

#tooltip {
        position: absolute;
        width: 200px;
        height: auto;
        padding: 10px;
        background-color: white;
        -webkit-border-radius: 10px;
        -moz-border-radius: 10px;
        border-radius: 10px;
        -webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
        -moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
        box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
        pointer-events: none;
}
#tooltip.hidden {
        display: none;
}
#tooltip p {
        margin: 0;
        font-family: sans-serif;
        font-size: 16px;
        line-height: 20px;
}

Step 3:Next step is to find out element on which you want tooltip. For this you have to find out left and top position of that element.You can find out element position using this code.

var getID = d3.select(this).attr("id");             
var div = document.getElementById(getID);
var rect = div.getBoundingClientRect                    

Note:

  • rect.left contais left position value and rect.top contains rect.top value.
  • ‘this’ represents your current selected element

Step 4: Now you know on which element you want tooltip then you need to use

    • .on(“mouseover”, yourFuntion)
    • .on(“mouseout”, yourFuntion)
        I used these funtion like this in my pie chart.
yourSelectedElement.on("mouseover", function(d) {
        // find the element position   
    var getID = d3.select(this).attr("id");                    
    var div = document.getElementById(getID);
    var rect = div.getBoundingClientRect();                                        
        // select your tooltip tag
    d3.select("#tooltip")
      .style("left", rect.left + "px") // left position
      .style("top", rect.top + "px")   // right position
      .select("#value")           // this id is your div tag id.
      .text(yourValue);
          //show tooltip     
    d3.select("#tooltip").classed("hidden", false);
    })    
    .on("mouseout", function() {
        //hide tooltip
        d3.select("#tooltip").classed("hidden", true);
    });
logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments