Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding width of text in Javascript [duplicate]

Is there a way to find the width of text in Javascript (jQuery is used, so happy to take advantage of any functions they provide) for a hidden element?

I want to have a graph of nodes. Each node has text inside and I want the nodes to have a width that accommodates the text up to a limit. So I essentially create hidden <div>'s with some html inside. Then I use jQuery to display those <div>'s on the graph at the right spots. It's important that I know the correct width ahead of time so I can construct the graph properly.

UPDATE: Just to clarify, I need to know how wide some text is while it's hidden. Blender gave an answer below, I'm hoping there's a less tricky way?

like image 965
at. Avatar asked Dec 10 '25 13:12

at.


1 Answers

What width do you mean? If you mean the <div> element's width, there's a handy function which does just what you need. Play with some of these:

$('#foo').width();
$('#foo').innerWidth();
$('#foo').outerWidth();

As for finding the width of a hidden element, I usually do this dirty trick:

var zIndex = $('#foo').css('z-index');

$('#foo').css('z-index', '-10');
$('#foo').css('position', 'absolute');
$('#foo').css('display', 'block');

var fooWidth = $('#foo').width();

$('#foo').css('display', 'none');
$('#foo').css('z-index', zIndex);

There must be a simpler way, though...

like image 50
Blender Avatar answered Dec 12 '25 01:12

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!