StackOverQuestions
StackOverQuestions

Reputation: 283

Dynamically resize div according to dynamic content?

I have a div called container which contains dynamically created content(paragraphs) through javascript. The problem is that the paragphs aren't shown on the div once they reach beyond the boundaries of the container. To solve this issue, I tried overflow but that just added x,y scrollbars.

What I'm trying to do is increase the height of the container after every parapgraph added i.e. when paragraph is added to container of height 20px, the container increases height to a further 40 px for next paragraph.

HTML

<div class="container"></div>

<a href="#" id="add">Add content</a>

CSS

.container {
width: 120px;
height: 20px;
display: inline-block;
margin-left: auto;
margin-right: auto;
/* overflow: auto; */  //As aforementioned, I'm not in favour of scrollbars
background-image: url('http://i.imgur.com/dfzk0TW.png');
}

Javascript

$(function () {
  $('#add').on('click', function () {
    $('<p>Text</p>').appendTo('#container');
  });
});

Any suggestions? Thank you!

Upvotes: 5

Views: 2603

Answers (2)

dadarya
dadarya

Reputation: 313

this code will get height of container div and than will add 20px in container div.

  $(function () {
      $('#add').on('click', function () {
        $('<p>Text</p>').appendTo('#container');
        heightWithPx =  $('#container').css('height');
        height = heightWithPx.substr(0,heightWithPx.length-2);
        newHeight = parseFloat(height)+20;
        $('#container').css('height',newHeight+'px');
      });
    });

Upvotes: 0

Nishit Maheta
Nishit Maheta

Reputation: 6031

Try this code

jsfiddle

remove height from css and use below code

$('<p>Text</p>').appendTo('.container');

remove # and put dot(.)

Upvotes: 5

Related Questions