Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery width and height not working on svg in firefox

I am trying to make SVG rectangle around SVG text. When i want to use .width() or .height() on SVG text, Chrome returns what I expect but Firefox does not. Here is link to jsfiddle demo I made.

$(document).ready(function(){
    var $rect = $(document.createElementNS('http://www.w3.org/2000/svg', 'rect'));
    var x = 50;
    var y = 50;
    var fontSize = 10;
    $rect.attr({
        'x' : x,
        'y' : y,
        'stroke' : 'black',
        'stroke-width' : 1,
        'fill' : 'white'
    });
    $rect.appendTo($("#svgArea"));

    var $svgText = $(document.createElementNS('http://www.w3.org/2000/svg', 'text'));
    $svgText.attr({
        'x': x,
        'y': y,
        'font-family' : 'verdana',
        'font-weight': 'bold',
        'font-size' : fontSize
    });

    var node = document.createTextNode("Lorem Ipsum");
    $svgText.append(node);
    $svgText.appendTo($("#svgArea"));

    var textWidth = $svgText.width();
    var textHeight = $svgText.height();

    $rect.attr({
        'x': x,
        'y': y - textHeight + 3,
        'width' : textWidth + 2,
        'height': textHeight
    });
});

html

    <svg height="200px" width="200px" id="svgArea">
</svg>

css

#svgArea{
    border: 1px solid black;
}
like image 264
tprieboj Avatar asked Jan 10 '16 22:01

tprieboj


1 Answers

JQuery width() and height() ultimately rely on properties and methods of the elements themselves. Chrome implements an offsetWidth in the SVGTextElement prototype which allows jquery to return a width. But it's not a standard property and Firefox doesn't implement it.

You can access width of svg text elements through the getBBox method. You can simply use it instead of jquery width. Like this:

var textWidth = $svgText.get(0).getBBox().width;
var textHeight = $svgText.get(0).getBBox().height;

See result: http://jsfiddle.net/nj413nbh/1/

See BBox specs: http://www.w3.org/TR/2011/REC-SVG11-20110816/types.html#__svg__SVGLocatable__getBBox

like image 83
Julien Grégoire Avatar answered Nov 08 '22 02:11

Julien Grégoire