To create a legend callback function for a chart, where I want to display a tooltip for the entire row when the user hovers over a legend item or click on a legend item. The issue I am facing is tooltip is applying only for the last appended child not for the entire row. Need to make the entire row display the tooltip.
Below is my code,
`legendCallback: function (chart) {
var legendTable = document.createElement('table');
legendTable.classList.add('legend-table');
chart.data.labels.forEach(function (label, index) {
var row = document.createElement('tr');
var colorBoxCell = document.createElement('td');
var colorBox = document.createElement('span');
colorBox.style.backgroundColor = colorList[index];
colorBox.classList.add('color-box');
colorBoxCell.appendChild(colorBox);
var labelCell = document.createElement('td');
var labelSpan = document.createElement('span');
labelSpan.textContent = labels[index].length > 15 ? labels[index].substring(0, 15) + '...' : labels[index];
labelCell.appendChild(labelSpan);
var costCell = document.createElement('td');
var costSpan = document.createElement('span');
costSpan.textContent = '(' + costs[index] + ')';
costSpan.style.color = '#2B0A3D';
costSpan.style.fontWeight = 'bold';
costCell.appendChild(costSpan);
row.appendChild(colorBoxCell);
row.appendChild(labelCell);
row.appendChild(costCell);
// Set the title attribute for the entire row
row.title = labels[index] +
'\ Cost: ' + costs[index];
// Add onmouseover and onclick events
row.addEventListener('mouseover', function (event) {
console.log('Clicked on legend item:', labels[index]);
row.title = labels[index] +
'\ Cost: ' + costs[index];
});
row.addEventListener('click', function (event) {
console.log('Clicked on legend item:', labels[index]);
row.title = labels[index] +
'\n Cost: ' + costs[index];
});
legendTable.appendChild(row);
});
return legendTable.outerHTML;
}`
I attempted to streamline and optimize the provided JavaScript code for a chart's legend callback, specifically focusing on creating legend items with tooltips. The primary goals were to simplify the structure, remove redundant code, and ensure tooltips for the entire row.