So here is what I have:
<path class="..." onmousemove="show_tooltip(event,'very long text
\\\n I would like to linebreak')" onmouseout="hide_tooltip()" d="..."/>
<rect class="tooltip_bg" id="tooltip_bg" ... />
<text class="tooltip" id="tooltip" ...>Tooltip</text>
<script>
<![CDATA[
function show_tooltip(e,text) {
var tt = document.getElementById('tooltip');
var bg = document.getElementById('tooltip_bg');
// set position ...
tt.textContent=text;
bg.setAttribute('width',tt.getBBox().width+10);
bg.setAttribute('height',tt.getBBox().height+6);
// set visibility ...
}
...
Now my very long tooltip text doesn't have a linebreak, even though if I use alert(); it shows me that the text actually DOES have two lines. (It contains a "\" though, how do I remove that one by the way?)
I can't get CDATA to work anywhere.
I suppese you alredy managed to solve it, but if someone is looking for similar solution then this worked for me:
There are 3 lines separated with linebreak.
This is not something that SVG 1.1 supports. SVG 1.2 does have the
textArea
element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementingtextArea
, but it does have auto-wrapped text.However, given that you already know where your linebreaks should occur, you can break your text into multiple
<tspan>
s, each withx="0"
anddy="1.4em"
to simulate actual lines of text. For example:Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.
I think this does what you want:
It splits the text on
\\\n
and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.
I have adapted a bit the solution by @steco, switching the dependency from
d3
tojquery
and adding theheight
of the text element as parameterWith the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321
That automatically does line breaks for long text svg for a given width in pixel.