NPS
NPS

Reputation: 6355

Change div's width by a value in JS

How to change div's width by a certain value, like this:

someDiv.style.width += "100px";

It works when I want to set a value (i.e. width = "100px") but the problem is with += operator.

Upvotes: 0

Views: 111

Answers (4)

Smern
Smern

Reputation: 19086

This would work for a vanilla javascript solution (since you didn't mention jquery):

var someDiv = document.getElementById("someDiv");
var w = 0;
if (typeof someDiv.clip !== "undefined") {
    w = someDiv.clip.width;
} else {
    if (someDiv.style.pixelWidth) {
        w = someDiv.style.pixelWidth;
    } else {
        w = someDiv.offsetWidth;
    }
}
someDiv.style.width = (w + 100) + "px";

Upvotes: 1

Dolo
Dolo

Reputation: 976

var currentwidth= $('#div').width();
$('#div').width(currentwidth +100);

http://jsfiddle.net/dolours/CME3Y/1/

Also you can use this https://stackoverflow.com/a/6179629/1479798

Upvotes: 0

Marco van Kimmenade
Marco van Kimmenade

Reputation: 398

That is because Javascript can't understand what "100px" + "100px" means, since those are string values.

I would do it like this using jQuery:

$(someDiv).width($(someDiv).width() + 100);

Upvotes: 0

Thomas Junk
Thomas Junk

Reputation: 5676

<div id="test" style="height:100px"></div>

var elem=document.getElementById("test");
height=parseInt(elem.style.height);
height+=100;
height+="px"
console.log(height);

Try the following http://jsfiddle.net/CME3Y/

Upvotes: 0

Related Questions