Reputation: 20882
I have the following HTML
<div id="tooltip" className="hidden">
<table>
<thead>
<tr>
<td colSpan="3">
<strong id="headDate"></strong>
</td>
</tr>
</thead>
<tbody id="toolTipBody">
</tbody>
</table>
</div>
Below the the D3 code that is working fine:
// ToolTip
d3.select('#tooltip')
.classed("hidden", false)
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + "px")
.select('#headDate').text(d0.date);
I need to inject/append HTML from D3 to the tool tip into the #toolTipBody element. It needs to be dynamic as the number of lines and names of lines can change (otherwise I could hard code the HTML and just use D3 .select & .text to make the updates.
How would I add say the following to #toolTipBody
<tr>
<td className="legend-color-guide"><div></div></td>
<td id="key">1.0E-6MHz</td>
<td id="value">46.50</td>
</tr>
thanks Adam
Upvotes: 0
Views: 2708
Reputation: 14591
You can change the HTML part dynamically as shown below.
d3.select('#tooltip').html(newHTML);
Reference: https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#html
Demo - (Mouse over the circle)
var testData = [{
data: [{
key: "1.0E-6MHz",
value: "46.50"
}, {
key: "2.0E-6MHz",
value: "50.50"
}],
date: "Apr 10",
color: "red"
}, {
data: [{
key: "1.0E-6MHz",
value: "46.50"
}, {
key: "2.0E-6MHz",
value: "50.50"
}, {
key: "1.8E-6MHz",
value: "10.50"
}],
date: "Feb 19",
color: "green"
}];
d3.select("svg")
.selectAll(".node")
.data(testData)
.enter()
.append("circle")
.attr("r", 5)
.attr("cx", function(d, i) {
return (i + 1) * 100
}).attr("cy", 50)
.on("mouseover", function(d) {
d3.select('#tooltip')
.classed("hidden", false)
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + "px")
.select('#headDate').text(d.date);
var newHtml = [];
d.data.forEach(function(h) {
newHtml.push('<tr>',
'<td id="key">' + h.key + '</td>',
'<td id="value">' + h.value + '</td>',
'</tr>');
});
d3.select('#tooltip')
.select("#toolTipBody").html(newHtml.join(""))
})
.on("mouseout", function(d) {
d3.select('#tooltip')
.classed("hidden", true);
});
#tooltip {
position: absolute;
background-color: #cecece;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="tooltip" class="hidden">
<table>
<thead>
<tr>
<td colSpan="3">
<strong id="headDate"></strong>
</td>
</tr>
</thead>
<tbody id="toolTipBody">
</tbody>
</table>
</div>
<svg width=400 height=200>
</svg>
Upvotes: 4