whytheq
whytheq

Reputation: 35557

Trying to use chaining to create wrapped text

I'm using D3 and SVG and am attempting to wrap some text by using attributes and chaining. This is my current code:

vis.append("svg:text")
    .attr("x", "0")
    .attr("y", "0")
    .attr("text-anchor", "middle")
    .append("svg.tspan")
    .attr("dy", ".35em")
    .text("Revenue Split")
    .text("for Current Month")
    .attr("transform", "translate(50,50)")
    .attr("class", "title");

The above is an attempt to translate this answer to using attr: https://stackoverflow.com/a/16701952/1179880

My attempt results in nothing showing on the screen.


update

With the help of the current two answers I've amended my code to the following:

vis.append("svg:text")
    .attr("x", "0")
    .attr("y", "0")
    .attr("class", "title")
    .attr("text-anchor", "middle")
    //.attr("transform", "translate(50,50)")
    .text("Revenue Split")
    .append("svg:tspan")
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .text("for Current Month")
    .attr("class", "title");

It appears to be heading in the right direction - although not quite as expected and on two distinct lines. The text appears as follows...

enter image description here

Upvotes: 1

Views: 60

Answers (3)

whytheq
whytheq

Reputation: 35557

This code by Mark in the comments above worked:

vis.append("svg:text")
      .attr("x", "0")
      .attr("y", "0")
      .attr("class", "title")
      .attr("text-anchor", "middle")
      .text("Revenue Split")
      .append("svg:tspan")
      .attr("dy", "1.1em")
      .attr("x", 0)
      .attr("text-anchor", "middle")
      .text("for Current Month")
      .attr("class", "title");

Upvotes: 0

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

You have to define the text for the text element and then define the text for the tspan element:

vis.append("text")
.attr("x", "0")
.attr("y", "0")
.attr("text-anchor", "middle")
.text("Revenue Split")
.append("tspan")
.attr("x", "0")
.attr("dy", ".35em")
.text("for Current Month")
.attr("class", "title");

Upvotes: 1

Robert Longson
Robert Longson

Reputation: 124059

  • You're using a . when you need a : as the d3 namespace separator for the tspan element (you get it right for the text element)
  • The transform presumably applies to the text element so needs to come before the tspan creation
  • The two text contents will overwrite, you can only have one per element.

Overall you probably want something like this...

vis.append("svg:text")
    .attr("x", "0")
    .attr("y", "0")
    .attr("text-anchor", "middle")
    .attr("transform", "translate(50,50)")
    .text("Revenue Split")
    .append("svg:tspan")
    .attr("dy", ".35em")
    .text("for Current Month")
    .attr("class", "title");

Upvotes: 2

Related Questions