Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Query width from a dynamic div

Status
Not open for further replies.

ackitsme

IS-IT--Management
Oct 15, 2002
21
US
I have need to be able to determine the width of a given displayed string in order to format other elements on the screen correctly.

My thought was that I could make a hidden div, dump the string to the div, then retrieve the width, something like this:

Code:
<script language='javascript'>
   getWidth( object ) {
      alert("The object's width is " + object.style.width);
   }
</script>

<div id='test' style='position:absolute; top:0; left:0; visibility:hidden'>This is a text string</div>
<button value="test" onclick="getWidth(document.getElementById('test'));">

The problem is that on both IE and Mozilla (I haven't tested others), it returns nothing for the width. This appears to be the case as long as the width was not initially specified.

Is there any way to query the width of the element if it is dynamically sized?

Thanks in advance.

-------------------------------------------------------------------------
Charlie Silverman
Sr. Systems Administrator
Globalstar, LLC

-------------------------------------------------------------------------
We now return you to your regularly scheduled reality.
 
Hi. Here's one example.

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/strict.dtd">[/URL]

<html>
<head>
<title>new document</title>

<script language="javascript" type="text/javascript">
<!--

function showWidth( el ) {
    alert( "The 'main' span has a width of " + el.offsetWidth );
}

-->
</script>

</head>

<body>
<span id="span">
text text text text text text text
<button onclick="showWidth(this.parentNode);">Click Me</button>
</span>
</body>

</html>

notice I used a span rather than a div. A div by default is a block element, and therefore will be the entire width of it's parent element unless otherwise stated explicitly with styles.

*cLFlaVA
----------------------------
[tt]insert funny quotation here.[/tt]
 
Thanks! That does the trick perfectly. What I'll do is put a span inside of a hidden div to accomplish the task that I'm looking for.

-------------------------------------------------------------------------
Charlie Silverman
Sr. Systems Administrator
Globalstar, LLC

-------------------------------------------------------------------------
We now return you to your regularly scheduled reality.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top