SciSpear
SciSpear

Reputation: 2008

The width seems to be zero (or NaN) always for an svg:text element in Firefox 15

I am using d3 to make a chart with multiple paths. I am displaying the path(s) description on the left hand side. The data & descriptions are dynamic so the size of the legend is naturally also dynamic, since it is not a big deal as long as I know the size of the text (just a minor adjustment to the domain/range). The problem is that I do not see an easy way to find the size of the text element in Firefox browsers.

Previously I was doing it with jquery's .width() but the clientWidth on the element is zero which seems to cause a NaNpx to be returned.

...
.on("click", function(){
    alert( $(this).width() ); // NaNpx
})
...

DEMO: Click on the words.

Upvotes: 3

Views: 1417

Answers (2)

Moshe.z
Moshe.z

Reputation: 301

Got the same problem. Seems like there is a bug in firefox (45.0) that <text> elements width inside SVG is always 0.

I overcame the bug by using a <tspan> element (inside the <text> element), and seems like the <tspan> has the correct width of text.

Hope it helps.

Upvotes: 0

SciSpear
SciSpear

Reputation: 2008

While writing up this question I found the solution (but still going to post it because I spent a very long time searching before finding it deep in a code example). Might be just because I am brand new to d3 and svg this month but there is a getBBox() method on the text element (most elements) that will generate an object with the width/height/x/y (and it really should be used instead of jquery for all svg dimensions).

Hope posting this will help anyone else who runs into this problem because it did not seem very visible to me.

DEMO

And in the example the ~~ is a flip-bit-operator, twice will actually work like a Math.floor() but will likely be faster in all browsers then .floor().

Upvotes: 5

Related Questions