59

I'm looking for a way to use a line break within a tooltip text element using d3.js.

.text("test" +  "</br>" + "test")

The above, and other similar efforts, don't seem to work.

There's a thread here that seems to answer it:

https://groups.google.com/forum/?fromgroups=#!topic/d3-js/GgFTf24ltjc

but the solution isn't very clear. How would .html be used in the above situation?

.text(.html("test" + "" + "test"))

didn't work?

Thanks

epascarello
  • 204,599
  • 20
  • 195
  • 236
Dan Harrington
  • 763
  • 2
  • 6
  • 7
  • Consider the solution I gave the link in the comment to the answer below. – Sergei Basharov Jun 20 '14 at 07:17
  • The solution is different if you talk about a element in an svg figure, or about any other text block (
    , , ..) outside svg. The accepted solution is for the later, see Sergei Basharov's link for the former.
    – tarulen Mar 07 '16 at 08:39
  • [This](http://stackoverflow.com/a/16701952/837229) answer had what I was looking for. – michaelgulak Sep 23 '16 at 17:40
  • 2
    What worked for me was to use .html (instead of .text, or .text(.html...): .on('mouseover', function(d) { return ( tooltip .html( d.country + '
    - population ' + d.population...
    – PatrickReagan Feb 16 '19 at 21:19

2 Answers2

23

Since you already know where you want to break the text, you could consider just adding separate elements.

.append("text")
  .attr("dy", "0em")
  .text("line 1")   // "line 1" or whatever value you want to add here.

And then for the second line, just add an offset

.append("text")
  .attr("dy", "1em") // you can vary how far apart it shows up
  .text("line 2")   // "line 2" or whatever value you want to add here.
lsu_guy
  • 1,525
  • 15
  • 12
1

Better to use 'tspan' for line 1 and line 2 both with attribure dy = 0em and dy = 1.2em