3

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?

at.
  • 50,922
  • 104
  • 292
  • 461

5 Answers5

1
$('#txt').width()

http://jsfiddle.net/Detect/jk97D/

Detect
  • 2,049
  • 1
  • 12
  • 21
1

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...

Blender
  • 289,723
  • 53
  • 439
  • 496
1

You can set the style of the divs to have no wrap white-space:nowrap (so, text is in one line) then get the width of each div, if more than the limit, set it to the limit and set the style to allow text wrapping `white-space:normal

Meligy
  • 35,654
  • 11
  • 85
  • 109
0

Just throwing in a non-JQuery answer to this. Assume I have a work div with id myworkerdiv and i have put my text in already.

var myDiv document.getElementById('myworkerdiv'),
width = myDiv.clientWidth || myDiv.scrollWidth;

You can also find out height as well, if your so included (clientHeight || scrollHeight).

Zoidberg
  • 10,137
  • 2
  • 31
  • 53
0

You could use something similar blender's method, but use the visibility css property rather than display. Visibility:hidden; keeps placement of the element, but just makes it invisible.

Ben
  • 2,917
  • 10
  • 28
  • 47