I am trying to implement the tool tip on hover of a particular node in force directed graph using d3 js.
Current Behavior: Tool tip is getting loaded but the text is not displayed properly, It is showing [object object] message instead of proper text message.
Expected Result: Tool tip should show the text in the below format:
Item Name: 'Item1',
Item Id: 'Item1',
Supplier: 'Supplier1'
How to achieve this ?
Working fiddle: Tool tip
function showToolTip(selectedNode) {
var itemDetails = [
{'Item': selectedNode.name},
{'Item Id': selectedNode.id},
{'status': 'Normal'},
{'Supplier': 'Supplier1'},
];
tooltip.transition().duration(200).style('visibility', 'visible')
.style('position', 'absolute').style('left', (d3.event.pageX) - 15 + 'px').style('top', (d3.event.pageY - 10) + 'px');
tooltip.selectAll('div').data(itemDetails).enter().append('div').text(function (d, i) { return d; });
}
function hideTooltip() {
tooltip.selectAll('*').remove();
tooltip.transition().duration(500).style('visibility', 'hidden');
}
The datum of each <div>
is an object, and you're trying to pass the whole object to the text()
method, hence the result you're seeing.
The best idea is dealing with the object inside the text()
method, specifying exactly what you want to show (keys and values), and how. Meanwhile, a very simple and naive solution is this:
.text(function (d, i) {
return Object.entries(d)[0].join(": ");
});
Here is the forked JSFiddle: https://jsfiddle.net/ou85b3n1/