jQuery animate() animate div height based on content

Description

jQuery animate() animate div height based on content

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Animate a Div Height According to Content</title>
<style>
    .box{//w w  w  .  j  a  v a2  s  .co m
        width: 350px;
        padding: 20px;
        border: 1px solid #ccc;
        background: #f2f2f2;
    }
    .box p{
        margin: 0;
        padding-top: 20px;
    }
    .box p:first-child{
        padding-top: 0;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    function animateHeight(){
        var newHeight = $(".box-inner").height();
        $(".box").animate({
            height: newHeight,
        }, 500);
    }
    $(".myButton").click(function(){
        $(".box").height($(".box-inner").height());
        var newContent = "<p>new content.</p>";
        $(".box-inner").append(newContent);
        animateHeight();
    });
});
</script>
</head>
<body>
<button class="myButton">Load Content</button>
<div class="box">
    <div class="box-inner">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus,
        dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus
        ac nisl bibendum scelerisque non non purus. Suspendisse varius nibh non
        aliquet sagittis. In tincidunt orci sit amet elementum vestibulum.
        Vivamus fermentum in arcu in aliquam. Quisque aliquam.
        </p>
    </div>
</div>
</body>
</html>



PreviousNext

Related