Parminder
Parminder

Reputation: 191

dynamically increasing height of div in javascript

I want to increase the height of the div tag on click of button. Every time a user clicks a button it should increase the height of that particular div tag, say by 200px or so..

HTML

      <div id="controls">
         <input type="button" onclick="incHeight()" id="btn" name="btn">
      </div>
      <div id="container" style="min-height:250px;"> &nbsp;</div>

The below script works properly

Javascript

      <script type="text/javascript">
        function incHeight()
        {
          document.getElementById("container").style.height = 250+'px';

        }
      </script>

But I want to do something like this, which is not working. The problem I think is the 'px' portion in the value. Anybody have any idea how to extract the INT portion of the value...

      <script type="text/javascript">
        function incHeight()
        {
          document.getElementById("container").style.height += 250;     
        }
      </script>

The problem is how do I get the '250' portion of the height value neglecting the 'px' in javascript..

Upvotes: 7

Views: 27489

Answers (4)

Mr.G
Mr.G

Reputation: 3559

Try this:

getElementById('container').setAttribute("style","height:500px");

or

function resize(element) {
  var height = 0;
  var body = window.document.body;
  if (window.innerHeight) {
      height = window.innerHeight;
  } else if (body.parentElement.clientHeight) {
      height = body.parentElement.clientHeight;
  } else if (body && body.clientHeight) {
      height = body.clientHeight;
  }
  element.style.height = ((height - element.offsetTop) + "px");
}

Upvotes: 2

GolezTrol
GolezTrol

Reputation: 116110

You can use a regular expression to only keep the numbers in the string:

var style = document.getElementById("container").style;
style.height = style.height.replace( /^\D+/g, '') + 'px';

Upvotes: 0

Powerslave
Powerslave

Reputation: 1428

Try something like

var container = document.getElementById('container');
container.style.height = (container.offsetHeight + 250) + "px";

In case offsetHeight is not working, try parsing the style.height for its numeric value instead.

var currentHeight = (container.style.height) ? (parseInt(container.style.height.match(/[0-9]+/)[0]) : container.offsetHeight;

Also, simply parseInt(container.style.height) might work

Upvotes: 3

Sergio
Sergio

Reputation: 28837

Try this:

function incHeight() {
    var el = document.getElementById("container");
    var height = el.offsetHeight;
    var newHeight = height + 200;
    el.style.height = newHeight + 'px';
}

Fiddle

Upvotes: 21

Related Questions