Sunday, January 15, 2017

Sample code to add tooltip to d3js chart

Last few weeks I have been writing the posts related to data visualisations using D3.js charting library. Initially I have shared the sample code to explain simple line chart. My previous post was about adding the grid lines to chart and in this post I want to help you all with an example of adding tooltips to our chart points.


Sample code to add tooltip to your charts



While working on charts, some time we come across the situations where we need to show data on mouseover event. Let's consider an example when we need to show x & y axis values of the data point on mouseover. In such situations adding a tooltip to chart points is best way to show such type of data. I usually create an empty DIV with class as tooltip and append it to the body. Then we need an event to unhide this DIV. In D3.js we can use "mouseover" event of the chart point to unhide the tooltip. Following is the sample code which you can use directly to show the tooltip on your chart. Lets learn with the following example.

Step 1 - Append an empty DIV to body
// Define the div for the tooltip
var tooltipDiv = d3.select("body").append("div") 
    .attr("class", "tooltip");
In above code we are adding an empty DIV to the body and giving it a class "tooltip" with attr method.

Step 2 - Apply style to the tooltip DIV
div.tooltip { 
    position: absolute;   
    text-align: center;   
    padding: 10px; 
    font: 12px sans-serif;  
    border-radius: 8px;   
    pointer-events: none;   
}
You can use your styling here to design skin of your tootltip element.

Step 3 - configure mouseover and mouseout events to hide/unhide tooltip
.on("mouseover", function(d) {  
         
// code block for tooltip
tooltipDiv.transition()  
    .duration(200)  
    .style("opacity", .9);  
tooltipDiv.html(d.year + ' : ' + d.sale) 
    .style("background", pointColor)  
    .style("left", (d3.event.pageX) - 30 + "px")  
    .style("top", (d3.event.pageY - 40) + "px"); 
})     
.on("mouseout", function(d) {  

tooltipDiv.transition()  
    .duration(500)  
    .style("opacity", 0); 
});    
This is last and most important step, we simply have to write a code to hide the tooltip on mouseover event and hide it on mouseout event. You have to write this code block while preparing the points on the chart. If you are confuse about how to place this code then please check the above demo link and check the working example.

Next > Highlight data points on mouseover

No comments:

Post a Comment