D3.js append tspan to text element

Shane G picture Shane G · Feb 14, 2017 · Viewed 8.6k times · Source

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);
}

Answer

javier picture javier · Feb 14, 2017

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", ...);