Javascript Getting a Div's Current Width

  • Ginja_Ninja
  • Student
  • Student
  • No Avatar
  • Joined: Dec 09, 2004
  • Posts: 89
  • Loc: UK
  • Status: Offline

Post February 17th, 2005, 3:47 am

Hi i want to make a javascript function that adds, 10 for example to the current width of an Div element.

I am not sure how to obtain the current width.

Any thoughts ?

TakeCare

G_N
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post February 17th, 2005, 3:47 am

  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Sep 07, 2004
  • Posts: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Post February 17th, 2005, 4:15 am

Give your div an ID so you can access it easily, and then use the "style" property to get the width:
Code: [ Select ]
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.style.width;
// now add 10 to the width
mydiv.style.width = curr_width + 10;
  1. var mydiv = document.getElementById("mydiv");
  2. var curr_width = mydiv.style.width;
  3. // now add 10 to the width
  4. mydiv.style.width = curr_width + 10;
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Sep 07, 2004
  • Posts: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Post February 17th, 2005, 4:40 am

If you tried the example above, you may be experiencing problems with the code. It may work in IE, but Firefox doesn't like it. Setting the DIV's initial width using CSS doesn't work for some reason - Firefox returns a null value for the "style.width" attribute. To work around this problem, set the initial width of the DIV in the "style" attribute of the DIV tag. This will ensure that Firefox gets a value for the initial width.
Here's the code I used to test it:
Code: [ Select ]
<html>
<head>
<style type="text/css">
div#mydiv {
    width: 100px;
    height: 100px;
    background-color: red;
}
</style>
<script language="JavaScript">
function addWidth() {
    var mydiv = document.getElementById("mydiv");
    var curr_width = parseInt(mydiv.style.width); // removes the "px" at the end
    mydiv.style.width = (curr_width + 10) +"px";
}
</script>
</head>
<body>
<input type="button" value="Make Bigger" onclick="addWidth()" />
<div id="mydiv" style="width:100px"></div>
</body>
</html>
  1. <html>
  2. <head>
  3. <style type="text/css">
  4. div#mydiv {
  5.     width: 100px;
  6.     height: 100px;
  7.     background-color: red;
  8. }
  9. </style>
  10. <script language="JavaScript">
  11. function addWidth() {
  12.     var mydiv = document.getElementById("mydiv");
  13.     var curr_width = parseInt(mydiv.style.width); // removes the "px" at the end
  14.     mydiv.style.width = (curr_width + 10) +"px";
  15. }
  16. </script>
  17. </head>
  18. <body>
  19. <input type="button" value="Make Bigger" onclick="addWidth()" />
  20. <div id="mydiv" style="width:100px"></div>
  21. </body>
  22. </html>
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • Ginja_Ninja
  • Student
  • Student
  • No Avatar
  • Joined: Dec 09, 2004
  • Posts: 89
  • Loc: UK
  • Status: Offline

Post February 17th, 2005, 5:15 am

one word - PERFECT-

Thanks alot thatsreally good

Take Care

G_N
  • RichB
  • Guru
  • Guru
  • User avatar
  • Joined: May 17, 2003
  • Posts: 1121
  • Loc: Boston
  • Status: Offline

Post February 17th, 2005, 5:16 am

Yeah, you can't retrieve the style values using ob.style.width unless they've been set using an inline style. There is a way around this that I came across last year while working on a problem with someone else here at Ozzu. It will retrieve the value whether it has been set inline or in an embedded or external (I think) style sheet, but the value has to be set via css before the function is called because IE will return a string value "auto" rather than the computed value of the actual width that mozilla will return if you don't set the value somewhere.

Code: [ Select ]
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
<!--
function getStyle(el, style) {
  if(!document.getElementById) return;
 
   var value = el.style[toCamelCase(style)];
 
  if(!value)
    if(document.defaultView)
      value = document.defaultView.
         getComputedStyle(el, "").getPropertyValue(style);
   
    else if(el.currentStyle)
      value = el.currentStyle[toCamelCase(style)];
  
   return value;
}

function setStyle(objId, style, value) {
  document.getElementById(objId).style[style] = value;
}

function toCamelCase( sInput ) {
  var oStringList = sInput.split('-');
  if(oStringList.length == 1)  
    return oStringList[0];
  var ret = sInput.indexOf("-") == 0 ?
      oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
  for(var i = 1, len = oStringList.length; i < len; i++){
    var s = oStringList[i];
    ret += s.charAt(0).toUpperCase() + s.substring(1)
  }
  return ret;
}

function increaseWidth(addToWidth, whichDiv){
  var theDiv = document.getElementById(whichDiv);
  var currWidth = parseInt(getStyle(theDiv, "width"));
  var newWidth = currWidth + parseInt(addToWidth);
  setStyle(whichDiv, "width", newWidth + "px");
}
// -->
</script>
<style type="text/css">
<!--
.testDiv {width: 200px; background-color:#ccc }
-->
</style>
</head>
<body>
<div id="test" style="width:200px; background-color:#ccc">Yada</div>
<div id="test2" class="testDiv">Yada</div>

<form name="testForm" action="">
<label> Add: <input name="newWidth" value="10" type="text" /></label><br>
<label> Add: <input name="testDiv" value="test" type="text" /></label><br>
<input type="button" value="Add to Width" onclick="increaseWidth(document.testForm.newWidth.value, document.testForm.testDiv.value)" />
</form>
</body>
</html>
  1. <html>
  2. <head>
  3. <title>Untitled</title>
  4. <script type="text/javascript">
  5. <!--
  6. function getStyle(el, style) {
  7.   if(!document.getElementById) return;
  8.  
  9.    var value = el.style[toCamelCase(style)];
  10.  
  11.   if(!value)
  12.     if(document.defaultView)
  13.       value = document.defaultView.
  14.          getComputedStyle(el, "").getPropertyValue(style);
  15.    
  16.     else if(el.currentStyle)
  17.       value = el.currentStyle[toCamelCase(style)];
  18.   
  19.    return value;
  20. }
  21. function setStyle(objId, style, value) {
  22.   document.getElementById(objId).style[style] = value;
  23. }
  24. function toCamelCase( sInput ) {
  25.   var oStringList = sInput.split('-');
  26.   if(oStringList.length == 1)  
  27.     return oStringList[0];
  28.   var ret = sInput.indexOf("-") == 0 ?
  29.       oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
  30.   for(var i = 1, len = oStringList.length; i < len; i++){
  31.     var s = oStringList[i];
  32.     ret += s.charAt(0).toUpperCase() + s.substring(1)
  33.   }
  34.   return ret;
  35. }
  36. function increaseWidth(addToWidth, whichDiv){
  37.   var theDiv = document.getElementById(whichDiv);
  38.   var currWidth = parseInt(getStyle(theDiv, "width"));
  39.   var newWidth = currWidth + parseInt(addToWidth);
  40.   setStyle(whichDiv, "width", newWidth + "px");
  41. }
  42. // -->
  43. </script>
  44. <style type="text/css">
  45. <!--
  46. .testDiv {width: 200px; background-color:#ccc }
  47. -->
  48. </style>
  49. </head>
  50. <body>
  51. <div id="test" style="width:200px; background-color:#ccc">Yada</div>
  52. <div id="test2" class="testDiv">Yada</div>
  53. <form name="testForm" action="">
  54. <label> Add: <input name="newWidth" value="10" type="text" /></label><br>
  55. <label> Add: <input name="testDiv" value="test" type="text" /></label><br>
  56. <input type="button" value="Add to Width" onclick="increaseWidth(document.testForm.newWidth.value, document.testForm.testDiv.value)" />
  57. </form>
  58. </body>
  59. </html>


You can test it by changing the div from "test" to "test2" - the first uses an inline style and the second a class in an embedded style sheet. However if you remove the width value in the css for either div IE will report an error and stop the script. I don't think there's anyway around this because I don't think you can retrieve the computed auto value from IE, but it should work as long as the div has an initial css value for the width, regardless of whether the css in inline, embedded or external.

The code for the functions that get and set the styles came from here:

http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp
http://dhtmlkitchen.com/learn/js/setstyle/index3.jsp
Free Programming Resources
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Sep 07, 2004
  • Posts: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Post February 17th, 2005, 5:19 am

Interesting stuff. I initially had my script block before my CSS block, so I swapped the two around to see if that would make any difference, but no.
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • RichB
  • Guru
  • Guru
  • User avatar
  • Joined: May 17, 2003
  • Posts: 1121
  • Loc: Boston
  • Status: Offline

Post February 17th, 2005, 5:23 am

Yep, those functions have come in handy once or twice, but they need careful testing with the different values because of the various browser quirks. For example, IE with return colors as hex triplets or literal values like "blue" - basically whatever you assign, but mozilla returns them as an rbg(100, 100, 100) style string regardless of how you set the property initially.
Free Programming Resources
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Sep 07, 2004
  • Posts: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Post February 17th, 2005, 5:59 am

One day, Firefox and IE will work together in perfect harmony. For an indication of that day, click here
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • RichB
  • Guru
  • Guru
  • User avatar
  • Joined: May 17, 2003
  • Posts: 1121
  • Loc: Boston
  • Status: Offline

Post February 17th, 2005, 6:11 am

heheh, I needed a laugh. thanks :)
Free Programming Resources
  • dimat
  • Student
  • Student
  • User avatar
  • Joined: Aug 02, 2006
  • Posts: 67
  • Loc: Kiev, Ukraine
  • Status: Offline

Post January 28th, 2008, 3:40 am

i found another solution:
div has property offsetWidth:
Code: [ Select ]
document.getElementsByTagName("div")["someDiv"].offsetWidth

witch represents its actual width. but! it is real only after all content is uploaded in div. for example, if it contains image:
Code: [ Select ]
<div id="someDiv"><img src="1024x768.png" /></div>

you can get width 40, because until image is not downloaded it is replaced with symbol of image witch width is 40. so if you want to calcutate all widthes of images on the website, you'd better do it on onLoad event.
Code: [ Select ]
<body onLoad="CalculateAllImageWidthes()">
....
</body>
  1. <body onLoad="CalculateAllImageWidthes()">
  2. ....
  3. </body>

P.S. offsetWidth is defined not only for div elements and works for all kinds of browsers.
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Sep 07, 2004
  • Posts: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Post January 28th, 2008, 6:32 am

Haha, if only I knew then what I know now! When I read the title of this post, I thought to myself - "Easy, use 'offsetWidth'", then I saw that I had actually replied to it in the first place!

Yep, if I was answering now, I'd suggest using offsetWidth. Using "style.width" only works if you set the width via CSS in the first place, which isn't an ideal solution, especially if you set the width using percentages etc.
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • dimat
  • Student
  • Student
  • User avatar
  • Joined: Aug 02, 2006
  • Posts: 67
  • Loc: Kiev, Ukraine
  • Status: Offline

Post January 28th, 2008, 7:22 am

this links goes neerly first when google "javascript div width", so i decided it would be good if visiters will find answer here
  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13455
  • Loc: Florida
  • Status: Offline

Post January 28th, 2008, 3:09 pm

I originally thought I'd be locking yet another old thread being bumped for spam.

This is a good example of when bumping old threads isn't such a bad idea.

I'm curious about this though,
Code: [ Select ]
document.getElementsByTagName("div")["someDiv"].offsetWidth


You can access a specific elements ID from getElementsByTagName like that ?
I thought only the numeric index was available cross-browser.
Code: [ Select ]
document.getElementsByTagName("div")[0].offsetWidth
Strong with this one, the sudo is.
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Sep 07, 2004
  • Posts: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Post January 29th, 2008, 2:46 am

Hmm, I didn't think that syntax would work either, however on thinking about it, I didn't see any reason that it wouldn't. I had just never used it before. I just tried it in Firefox, IE6 and Opera and it seems to work fine. I suppose that's a bit more robust than simply specifying the index of the item you want to change (index is more likely to change than the element ID).

Learn something new everyday.
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • josepharistotil
  • Born
  • Born
  • No Avatar
  • Joined: Sep 13, 2008
  • Posts: 1
  • Status: Offline

Post September 13th, 2008, 1:06 am

Are you try this as following?
for finding width
Code: [ Select ]
document.getElementById("<DivName>").offsetWidth;

for fiding height
Code: [ Select ]
document.getElementById("<DivName>").offsetHeight;
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post September 13th, 2008, 1:06 am

Post Information

  • Total Posts in this topic: 18 posts
  • Users browsing this forum: No registered users and 169 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.