Search code examples
javascriptd3.jssvgtooltipnewline

line break for d3 circle title tooltipText


I'm using d3's svg, when the tooltipText for a circle title is "line1\nline2", the line is not broken into 2, but just showing the raw text "line1\nline2".

tried Add line break within tooltips and Can you insert a line break in text when using d3.js?, but not working

Is there a way to have it show 2 lines instead of 1 line with raw text?

i.e. \n got interpreted. I assume changing backend response will not help since it's a bug of presentation layer.

Thanks a lot.

Trial-1, replace with "&#013" or "\u000d"

svgContainer.selectAll("g.node").each(function() {
 var node = d3.select(this);
 var tooltipText = node.attr("name"); // tooltipText is "line1\nline2"
 // trying to use entity code, not working. Also tried to replace with "\u000d"
 var tooltipText = node.attr("name").replace("\\n", "&#013"); 
 if (tooltipText) {
   node.select("circle").attr("title", tooltipText);
 }

also tried add .attr("data-html", "true") Add line break to tooltip in Bootstrap 3

svgContainer.selectAll("g.node").each(function() {
 var node = d3.select(this);
 var tooltipText = node.attr("name"); // tooltipText is "line1\nline2"
 // trying to use entity code, not working. Also tried to replace with "\u000d"
 var tooltipText = node.attr("name").replace("\\n", "&#013"); 
 if (tooltipText) {
   node.select("circle")
     .attr("data-html", "true")
     .attr("title", tooltipText);
 }

Solution

  • I just figured it out myself, after referencing How to make Twitter bootstrap tooltips have multiple lines?

    I have to change below 2 places:

    1. change \n to be <br />
    2. add attribute .attr("data-html", "true")

    working version:

    svgContainer.selectAll("g.node").each(function() {
     var node = d3.select(this);
     var tooltipText = node.attr("name");
     var tooltipText = node.attr("name").replace("\\n", "<br />"); 
     if (tooltipText) {
       node.select("circle")
         .attr("data-html", "true")
         .attr("title", tooltipText);
     }