Javascript Getting a Div's Current Width

  • Ginja_Ninja
  • Student
  • Student
  • Ginja_Ninja
  • Posts: 89
  • Loc: UK

Post 3+ Months Ago

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
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 2391
  • Loc: Edinburgh, Scotland

Post 3+ Months Ago

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;
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 2391
  • Loc: Edinburgh, Scotland

Post 3+ Months Ago

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>
  • Ginja_Ninja
  • Student
  • Student
  • Ginja_Ninja
  • Posts: 89
  • Loc: UK

Post 3+ Months Ago

one word - PERFECT-

Thanks alot thatsreally good

Take Care

G_N
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

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
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 2391
  • Loc: Edinburgh, Scotland

Post 3+ Months Ago

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.
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

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.
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 2391
  • Loc: Edinburgh, Scotland

Post 3+ Months Ago

One day, Firefox and IE will work together in perfect harmony. For an indication of that day, click here
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

heheh, I needed a laugh. thanks :)
  • dimat
  • Student
  • Student
  • User avatar
  • Posts: 67
  • Loc: Kiev, Ukraine

Post 3+ Months Ago

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
  • Posts: 2391
  • Loc: Edinburgh, Scotland

Post 3+ Months Ago

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.
  • dimat
  • Student
  • Student
  • User avatar
  • Posts: 67
  • Loc: Kiev, Ukraine

Post 3+ Months Ago

this links goes neerly first when google "javascript div width", so i decided it would be good if visiters will find answer here
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13504
  • Loc: Florida

Post 3+ Months Ago

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
  • katana
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 2391
  • Loc: Edinburgh, Scotland

Post 3+ Months Ago

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.
  • josepharistotil
  • Born
  • Born
  • josepharistotil
  • Posts: 1

Post 3+ Months Ago

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

for fiding height
Code: [ Select ]
document.getElementById("<DivName>").offsetHeight;
  • mlarson154
  • Novice
  • Novice
  • User avatar
  • Posts: 15
  • Loc: Utah, USA

Post 3+ Months Ago

I know this is an old post, but I've seen a lot of posts on many forums regarding changing the width via .style.width without any clear answer as to why it doesn't work. What I found is that the <div> must load before you can change it, so calling your function in the header doesn't return anything since the <div> itself hasn't been loaded.

Therefore, call your function AFTER the <div>:
Code: [ Select ]
<head>
<script type="text/javascript"> function WidthChange()
{
document.getElementById("DivName").style.width = '100px';
}
</script>
</head>
<body>
<div id="DivName">
<script type="text/javascript">WidthChange()</script>
...
  1. <head>
  2. <script type="text/javascript"> function WidthChange()
  3. {
  4. document.getElementById("DivName").style.width = '100px';
  5. }
  6. </script>
  7. </head>
  8. <body>
  9. <div id="DivName">
  10. <script type="text/javascript">WidthChange()</script>
  11. ...


You can specify the function call at any time AFTER the div line, so you can put it down near the </body> tag if you want.

This is how I figured out I could use .style.width. Anybody have a correction to this? I could not find ANY way to make the function call prior to the div line.
  • creatino
  • Born
  • Born
  • creatino
  • Posts: 1

Post 3+ Months Ago

Hey guys,

Thanks for both methods, both make sense and were the only helpful results after much googling. I'm quite new to CSS and JS but a good actionscripter.

I'm testing both methods and seem to be getting different values from them. Besides that, Firefox 3.5.4 doesn't want to show me the two following alerts I'm using while testing: Safari does it fine. Any ideas why that might be? I need that value as a basis for some js animation.

HTML Code: [ Select ]
<script type="text/javascript">
   alert(getStyle(item3, "width"));
   alert(document.getElementById("item1").offsetWidth);
</script>
  1. <script type="text/javascript">
  2.    alert(getStyle(item3, "width"));
  3.    alert(document.getElementById("item1").offsetWidth);
  4. </script>


Help appreciated, thnx!
Moderator Remark: Added [code] tags
  • dbind
  • Born
  • Born
  • dbind
  • Posts: 1

Post 3+ Months Ago

@RichB: your toCamelCase() function could be greatly enhanced and simplified by using regular expressions:

function toCamelCase( sInput ) {
return sInput.replace(/-([a-zA-Z])/g, function(s, s1){
return s1.toUpperCase();
});
};

Hope it helps someone.

[quote="RichB"]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:

[...]
[...]

Post Information

  • Total Posts in this topic: 18 posts
  • Users browsing this forum: No registered users and 38 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
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.