D3.js append tspan to text element
Mia Lopez
I have a D3 bar chart. When I mouseover of one of the bars, text appears.
But I would like another line of text to also appear. For this I need to append a <tspan> element.
I have seen examples, but can't get <tspan> to append to the text element.
The Graph is here, and full code on github.
'text' is appended and 'tspan' is appended to that,
g.selectAll(".bar") .data(data) .enter().append("rect") .style("fill", function(d) { return colorScale(d.intensity); }) .attr("class", "bar") .attr("x", function(d) { return x(d.date); }) .attr("y", function(d) { return y(d.distance); }) // .attr("width", x.bandwidth()) .attr("width", function(d) { return dur(d.duration); }) // .attr("width", 6) .attr("height", function(d) { return height - y(d.distance); }) .on("mouseover", handleMouseOver) .on("mouseout", handleMouseOut); t = g.append('text') .attr('x', 9) .attr('dy', '.35em'); ts = g.append('tspan') .attr('x', 9) .attr('dy', '.35em');The JS function handleMouseOver
function handleMouseOver(d) { d3.select(this) .style("fill", "lightBlue") g.select('text') .attr("x", x(d.date) + dur(d.duration + 5)) .attr("y", y(d.distance) + 10) .text(d.distance + "m"); ts.text("blah") .attr("x", x(d.date) + dur(d.duration + 5)) .attr("y", y(d.distance) + 30);
} 1 2 Answers
Try the following:
To append:
t = g.append('text') .attr('x', 9) .attr('dy', '.35em');
ts = g.append('tspan') .attr('x', 9) .attr('dy', '.35em');and then on the hanldeMouseOver:
ts.text("blah") .attr("x", ...) .attr("y", ...); 2 I got it by appending tspan in the function,
function handleMouseOver(d) { d3.select(this) .style("fill", "lightBlue") g.select('text') .attr("x", x(d.date) + dur(d.duration + 5)) .attr("y", y(d.distance) + 10) .text(d.distance + "m") .append('tspan') .text(d.number) .attr("x", x(d.date) + dur(d.duration + 5)) .attr("y", y(d.distance) + 30) .append('tspan') .text(d.date) .attr("x", x(d.date) + dur(d.duration + 5)) .attr("y", y(d.distance) + 50);
}There is no tspan elsewhere.
Working example here
Thanks