Chipe Chipe - 3 months ago 15
jQuery Question

How to get container to have height grow up, not down when content is added?

I have a container that allows users to add more text to it through an

input
. The container is
position:absolute
with a
top
on it. When a user adds to the container through the
input
the height of the container grows, but downwards. Is there a way to get the bottom of the container to stay where it is, and have the height grow upwards.

In this fiddle example I will provide I have tried doing a
bottom
instead of a
top
, and that seems to work how I want. However, in my app I have calculations that are mounting the app to the page, and
bottom
is something I cant always count on, but
top
is something that I can count on and the app mounts correctly depending on screen width and edge detection calculations.

So is there a way to have it grow up with a
top
?



$('form').submit(function(e){
e.preventDefault();
var inputVal = $('.input').val();
var html = '<div class="content">'+inputVal+'</div>'
$('.container').append(html)
});

.container{
border:1px solid #000;
width:300px;
position:absolute;
top:300px;
}
.content{
padding:10px 5px;
}

<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<form>
<input type="text" class="input" placeholder="type, hit enter">
</form>

<div class="container">
<div class="content">Some Content</div>
</div>




Answer

you need calculate top position of container by subtracting changed height of it (https://jsfiddle.net/hqb4kmtm/13/):

$('form').submit(function(e){
    e.preventDefault();
    var inputVal = $('.input').val();
    var html = '<div class="content">'+inputVal+'</div>'
    var container = $('.container');
    var heightBefore = container.height();
    container.append(html);
    var heightAfter = container.height();
    container.css({top:container.offset().top + heightBefore - heightAfter});
});