Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a pixel width from a span programmatically with jquery

I'm trying to do something like:

 $('<span>random text in here</span>').width()

But the width it's returning is 0. (The reason I'm trying to do this is to get the pixel width of a given text.)

How would I get this width, programmatically?

Thanks

like image 321
Shai UI Avatar asked Nov 07 '12 16:11

Shai UI


People also ask

How do you find the width of a span element?

Assigning the Width of the Span ElementYou can assign a width to the span after setting its “display” property to either “block” or “inline-block.” Moreover, you can use the float and width properties to assign a width to the same element. The width of span is affected by the default display property of the same.

How do you find pixel width?

Find the image file in your Finder, right click the image and select Get Info. A pop-up window will open with the dimensions of your image displaying in the More Info section. The dimensions show the pixel height and width of your photo.

How to get content width in JavaScript?

getBoundingClientRect() method To get the width and height of the element you should use the corresponding property names. The width and height properties of the getBoundingClientRect() method will return the value based on the CSS box-sizing property of the element.

How to get width of character in JavaScript?

The clientWidth property is used to get the width of its element. This value will represent the width of text in pixels.


1 Answers

You have to have it rendered.

You may do this :

var s = $('<span>random text in here</span>');
s.appendTo(document.body);
var w = s.width();
s.remove();

Demonstration

Note that :

  • nothing is displayed if you do this like I do in one go. For all practical purposes, nothing is inserted in the DOM,
  • you could also use an in memory canvas but it wouldn't handle anything more complex than simple text and wouldn't take into account your span's css settings.

Here's the solution measuring the width of some text using an in memory canvas :

var canvas = document.createElement('canvas');
var c = canvas.getContext('2d');
// set here c.font to adjust it to your need
var w = c.measureText('random text in here').width;

Demonstration

I would use the first one in the general case but it might depend on why you want to measure the text.

like image 85
Denys Séguret Avatar answered Oct 23 '22 04:10

Denys Séguret