Asked
Updated
Viewed
289.9k times

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

add a comment
0

17 Answers

  • Votes
  • Oldest
  • Latest
Answered
Updated

Give your div an ID so you can access it easily, and then use the "style" property to get the width:

var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.style.width;
// now add 10 to the width
mydiv.style.width = curr_width + 10;
add a comment
0
Answered
Updated

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:

<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>
add a comment
0
Answered
Updated

one word - PERFECT-

Thanks alot thatsreally good

Take Care

G_N

add a comment
0
Answered
Updated

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.

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

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.

add a comment
0
Answered
Updated

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.

add a comment
0
Answered
Updated

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.

add a comment
0
Answered
Updated

One day, Firefox and IE will work together in perfect harmony.

add a comment
0
Answered
Updated

heheh, I needed a laugh. thanks 🙂

add a comment
0
Answered
Updated

i found another solution:
div has property offsetWidth:

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:

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

<body onLoad="CalculateAllImageWidthes()">
....
</body>

P.S. offsetWidth is defined not only for div elements and works for all kinds of browsers.

add a comment
0
Answered
Updated

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.

add a comment
0
Answered
Updated

this links goes neerly first when google "JavaScript div width", so i decided it would be good if visiters will find answer here

add a comment
0
JO
184 4
Answered
Updated

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,

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.

document.getElementsByTagName("div")[0].offsetWidth
add a comment
0
Answered
Updated

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.

add a comment
0
Answered
Updated

Are you try this as following?
for finding width

document.getElementById("<DivName>").offsetWidth;

for fiding height

document.getElementById("<DivName>").offsetHeight;
add a comment
0
Answered
Updated

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

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

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.

add a comment
0
Answered
Updated

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.

<script type="text/javascript">
	alert(getStyle(item3, "width"));
	alert(document.getElementById("item1").offsetWidth);
</script>

Help appreciated, thnx!

add a comment
0
Answered
Updated

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

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.

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

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:

[...]
[...]

add a comment
0