1

Is There a way to animate the height of div when it's content was changed (by script and \ or css)?

div {
  width:100px;
  }

#b {
  display:none;
  }

.wrapper.switch #a {
  display:none;
  }

.wrapper.switch #b {
  display:block;
  }
<div class="wrapper">
  <div id="a">
    Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text 
    </div>
  <div id="b">
    Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text 
    </div>
  
  <button onclick="document.querySelector('.wrapper').classList.toggle('switch');">swich</button>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
  • possible duplicate of [webkit-transition height for a div with a dynamic changing height based on content?](http://stackoverflow.com/questions/6588510/webkit-transition-height-for-a-div-with-a-dynamic-changing-height-based-on-conte) – enguerranws Nov 06 '14 at 10:33
  • Although the question might be similar I don't see why it would be a duplicate of that question. – Alex Nov 06 '14 at 12:15

1 Answers1

0

I think this script will help you:

<html lang="en">
<head>
<meta charset="UTF-8">
<title>stackoverflow</title>
<style type="text/css">
    .box{
        width: 350px;
        padding:20px;
        border: 1px solid #ccc;

    }
  .box p{
        margin: 0;
        padding-top: 20px;
    }
    .box p:first-child{
        padding-top: 0;
    }

</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    // Defining the function
    function animateHeight(){
        var newHeight = $(".box-inner").height();
        $(".box").animate({
            height: newHeight,
        }, 500);
    }
    $(".load-more").click(function(){
        // Setting the initial height of the box
        $(".box").height($(".box-inner").height());

        // Appending box with new content and animate the height
        var newContent = "<p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text</p>";
        $(".box-inner").append(newContent);
        animateHeight();
    });
});
</script>
</head>
<body>
<button class="load-more">Switch</button>
<p>Height Changes Whenever you click</p>
<div class="box">
    <div class="box-inner">
        <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
        </p>
    </div>
</div>
</body>
</html>
Tanul
  • 354
  • 4
  • 20