0

I have the following code :

$(document).ready(function(){
  $("#add").click(function(){
    $("#content").append("<p>New text</p>");
  });
});
#content{
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  padding: 15px;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<p>TEXT</p>
</div>
<button id="add">Add text</button>

I expect when I click on the button add, the content div will have a transition when he expand. I have tried with the following animation css :

-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
transition: all .5s ease;

I would like to add a transition to the div

I also tried with .show('slow');

doğukan
  • 23,073
  • 13
  • 57
  • 69
executable
  • 3,365
  • 6
  • 24
  • 52
  • This has nothing to do with the border...you're changing the height of the div and you can't transition to/from `auto`. – Paulie_D Apr 22 '20 at 14:30

1 Answers1

2

You can do this using another element.

$(document).ready(function() {
  function initBorder() {
    $("#content-border").css({
      height: $("#content").outerHeight(),
      width: $("#content").outerWidth(),
    });
  }

  initBorder();

  $("#add").click(function() {
    $("#content").append("<p>New text</p>");
    initBorder();
  });
});
#content {
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  padding: 15px;
  position: relative;
}

#content-border {
  position: absolute;
  left: 0;
  top: 0;
  border: 1px solid black;
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
  <p>TEXT</p>
  <div id="content-border"></div>
</div>

<button id="add">Add text</button>

We can use the fade function for a smoother transition.

$(document).ready(function() {
  function initBorder() {
    $("#content-border").css({
      height: $("#content").outerHeight(),
      width: $("#content").outerWidth(),
    });
  }

  initBorder();

  $("#add").click(function() {
    $("#content").append("<p>New text</p>");
    $("#content").find("p").last().fadeOut(0).fadeIn(500);
    initBorder();
  });
});
#content {
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  padding: 15px;
  position: relative;
}

#content-border {
  position: absolute;
  left: 0;
  top: 0;
  border: 1px solid black;
  -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  transition: all .5s ease;
  box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
  <p>TEXT</p>
  <div id="content-border"></div>
</div>

<button id="add">Add text</button>
doğukan
  • 23,073
  • 13
  • 57
  • 69