I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example. These tooltips are not persistent and lack interactivity.
After discovering some code on Stack Overflow (link here) that incorporates a timeout and CSS modifications to make the tooltips persist and enable user interaction, I faced an issue with closing the tooltip once it appears. I wanted to implement a mechanism where the tooltip could be closed by clicking anywhere on the chart or the tooltip itself, or via a defined timeout. It's bothersome to have tooltips lingering on the chart indefinitely after their initial appearance.
You can view the implementation of this code on this JSFiddle.
I assumed there should be a function that I could call or override for handling the tooltip closure. I experimented with adding an onclick feature so that clicking on a data point triggers an action, but I struggled to achieve the desired outcome. To uncover how to incorporate onclick functionality, I referred to this resource.
data: {
columns: [ ['data1', 40, 50, 60, 70, 80] ],
types: { data1: 'bar'},
onclick: function(e) { alert(e.value); }
}
The method through which the tooltip closure would be initiated isn't a crucial concern for me. Below is the code snippet from the JSFiddle exemplifying interactions with the tooltip and its persistence without automatic closure.
CSS:
.c3-tooltip-container {
background-color: #ccc;
border: solid 1px black;
padding: 20px;
pointer-events: auto !important;
}
JS:
var features = dates = defects = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
];
var chart = c3.generate({
data: {
columns: [
['data1', 30000, 20000, 10000, 40000, 15000, 250000],
['data2', 100, 200, 100, 40, 150, 250]
],
},
tooltip: {
position: function () {
var position = c3.chart.internal.fn.tooltipPosition.apply(this, arguments);
position.top = 0;
return position;
},
contents: function (data, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value;
text = "<div id='tooltip' class='d3-tip'>";
title = dates[data[0].index];
text += "<span class='info'><b><u>Date</u></b></span><br>";
text += "<span class='info'>" + title + "</span><br>";
text += "<span class='info'><b><u>Features</u> : </b> " + features[data[0].index] + "</span><br>";
text += "<span class='info'><b><u>Enhancements</u> : </b> " + defects[data[0].index] + "</span><br>";
text += "</div>";
return text;
}
}
});