1

Using D3 to create a force graph. I wish to click a button and a rectangle appears (which I have done). Now I want to append this rectangles text with a few lines of text.

I have three sentences I wish to show, one on each line, so I know where the line breaks should be.

I have tried these :

.text("test" + "\n" + "should be on second line");

.text("test" + "\\n" + "should be on second line");

.text("test" + "<br/>" + "should be on second line");

.html("test" + "\n" + "should be on second line");

.html("test" + "\\n" + "should be on second line");

.html("test" + "<br/>" + "should be on second line");

None of them seem to work and I am unsure why. I have searched around and people are sort of doing hacks to get around this. Surely there is an easier way ?

rekoDolph
  • 813
  • 1
  • 9
  • 31
  • is it http://bl.ocks.org/mbostock/4062045 ? – Nitish Kumar Jan 12 '15 at 10:56
  • yeah @NitishKumar but that doesnt really matter. All I want to do is edit the text on a svg:rect to have text on multiple lines – rekoDolph Jan 12 '15 at 10:58
  • http://stackoverflow.com/questions/4991171/auto-line-wrapping-in-svg-text – Robert Longson Jan 12 '15 at 11:05
  • Why do quesitons on this tag never get closed, this has been asked so many times... [How to linebreak an svg text in javascript?](http://stackoverflow.com/questions/19447321/how-to-linebreak-an-svg-text-in-javascript) – Mark Jan 12 '15 at 15:34
  • @Mark I was looking to see if there was an easier way since I couldnt find one. But ended up hacking it abit in the end as there isnt an easy way. – rekoDolph Jan 13 '15 at 22:47

1 Answers1

2

I have figured it out and works for me as I am using D3. I created an array (of the text I wish to show), then made a function that splits the array up on seperate lines.

var popUpTextArray = ["first line", "second line", "third line"];

function textMultipleRows(textArray, area, xPos, yPos){

    for(i=0;i<textArray.length;i++){
        d3.selectAll(area) //-area you wish to append the text to
        .append("text")
        .classed("popUpTextLeft", true) //-CSS class for the text
        .attr("x", xPos)
        .attr("y", yPos+(i*20)) //-new line when going through the loop
        .text(textArray[i]); //-goes through each element in the text array
    }   
}

textMultipleRows(popUpTextArray, "#window1", 300,200);

It is a bit hacky and it's made up of D3 so I dont know if alot of people will use it but as I said it works perfectly for me.

rekoDolph
  • 813
  • 1
  • 9
  • 31