Height and width properties in JQuery not functioning properly on SVG elements in Firefox

I am attempting to create an SVG rectangle around SVG text. I have noticed that when using .width() or .height() on SVG text, Chrome provides the expected results while Firefox does not. Here is a link to a demo I created on jsfiddle.

$(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;
}

Answer №1

When it comes to determining width and height using JQuery, it all boils down to the properties and methods of the elements themselves. Interestingly, Chrome has included an offsetWidth in the SVGTextElement prototype which JQuery can utilize to calculate width, but this feature is not standardized and Firefox does not support it.

If you need to find the width of SVG text elements, you can rely on the getBBox method instead. Here's an example:

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

Check out the result here: http://jsfiddle.net/nj413nbh/1/

You can refer to the BBox specifications here: http://www.w3.org/TR/2011/REC-SVG11-20110816/types.html#__svg__SVGLocatable__getBBox

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for aligning tooltips with the locations of dragged elements

One of my projects involves a simple drag element example inspired by Angular documentation. The example features a button that can be dragged around within a container and comes with a tooltip. <div class="example-boundary"> <div ...

Incorporating CSS classes conditionally in an Angular child component using input values

I am currently using a list component: <section class="p-10 flex flex-col gap-10"> <p class="text-xl font-black text-blue-700">Transfer history</p> <div class="flex flex-col gap-10"> @for(item o ...

Understanding the separation and communication techniques in Vue.js components

I recently developed a small vuejs application and I find myself getting confused with the functioning of components. Here is the code snippet that I have been working on: <div id="app"> <div v-if="loggedIn"> <nav> <r ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...

How to send all items from a listbox to a controller in MVC 5

Having an issue passing all items in a listbox back to the controller. The controller remains empty even when I declare another variable for it as List. It only passes back the selected value, but I want to pass back all values. I am working with 2 listbo ...

CSS declarations that have not been acknowledged or acknowledged

While working on a client's stylesheet today, I came across the following code: p { -webkit-hyphens: auto; -webkit-hyphenate-character: "\2010"; -webkit-hyphenate-limit-after: 1; -webkit-hyphenate-limit-before: 3; -moz-hyphens: manual; orphans: ...

Locating specific text within a span using Python Selenium

Struggling to find a specific text within a span element, which is crucial for a successful test. I am unable to make it work on my own. Can anyone provide assistance? I need to extract the text inside the span again to showcase that the update I am search ...

Retrieving the function or state of a component within a higher-order component (HOC) wrapper

Hey there! I have a situation where Component A, which extends React.component, is wrapped with a higher order Component B. Now, in the methods of Component B, I need to either setState for Component A or call a function in A to do the setState. How can I ...

CSS: Inaccurate positioning and border-radius causing gap between div and border-bottom

My goal was to create a card game with multicolored, double-sided borders, but I encountered issues when trying to implement this feature. Initially, I attempted to use an onclick event to change the border color, but it didn't work as expected. I fi ...

How can you implement the functionality of Lodash's _.countBy using just ES6?

Consider the following array of arrays const data = [[150, 1], [300, 2], [430, 1]] If I were to use Lodash's countBy, I could achieve the same result with ES6 syntax by writing { ...data.reduce((acc, row) => ({ ...acc, [row[1]]: (acc[row[1]] || 0) ...

Can multiple background images be handled by Firefox/Opera when positioned?

Encountering difficulties with certain background images not showing in Firefox and Opera, while all other browsers are working as expected (except IE, which always presents its own challenges). As of now, Opera is refusing to accept multiple background i ...

Waiting for state changes in React by using the UseState Hook

I am currently working on a function that manages video playback when clicked, and I need to set consecutive states using the useState hook. However, I want to ensure that the first state is completed before moving on to the next setState without relying ...

Enhance the CSS styling for the React-Calendly integration in a React project

I am trying to customize the CSS of an Inline Widget called React Calendly. I have attempted to use React Styled Component Wrapper, Frame React Component, and DOM javascript but unfortunately, the design changes are not reflecting as desired. Specifically, ...

Rearrange element's placement using Jquery Drag & Drop

I am experiencing difficulties in positioning my elements after a drop event. Within my "list" of divs... In order to keep the divs together and update the list, I utilize jQuery's append function to move the element from the list to its designated ...

Troubleshooting: Bootstrap Modal in .NET MVC not appearing on screen

Below is the code that manages order quotes and includes an if statement. The objective is to display an error message using TempData and Bootstrap Modal if the product quantity in the order exceeds the stock quantity. However, despite TempData not being n ...

Properly handling curves in THREE.JS to ensure efficient disposal

I am facing a challenge with managing memory in my project. I have a dynamic sphere with moving points on it, and I am creating curves to connect these points. Here is an illustration of the process: https://i.sstatic.net/PGWuU.jpg As the points are cons ...

choose the li element that is located at the n-th position within

Need help with HTML code <div class="dotstyle"> <ul> <li class="current"><a href="javascript:void(0)"></a></li> <li><a href="javascript:void(0)"></a></li> <li><a href="javasc ...

The absence of a semi-colon in JSLint

I encountered an error message indicating a semicolon is missing, however I am unsure of where to place it. Here is the snippet of code: $('.animation1').delay(350).queue(function(){ $(this).addClass("animate-from-top") }); ...

Ever-evolving message in constant motion

I need help creating a dynamic message that changes every 10 seconds without reloading the page. I have a PHP array set up like this: arr[0] = "abc"; arr[1] = "def"; arr[2] = "ghi"; arr[3] = "jkl"; I want to use AJAX or jQuery to display different str ...

A basic structure for a JSON array

Perhaps my next question may appear silly, but I'll ask it anyway :) Here is the structure in question: { "name": "Erjet Malaj", "first_name": "Erjet", "work": [ { "employer": { "id": "110108059015688 ...