Search code examples
javascripthtmlcsssmoothinginsertion

How to have smooth movements when inserting a new element?


I insert a new div element in the middle of the others, and I want the others to move to their new position in a fluid way and not suddenly as is currently the case.

Here is my code in action: https://codepen.io/BigEiffelTower/pen/vYBgqZq

<div id="top">
  Top of the page
</div>

<div id="middle">

</div>

<div id="bottom">
  <form> 
    <input type="button" value="Add an element">
  </form>
  End of the page
</div>
#top, #middle, #bottom {
  font-size: 1.5em;
  border: 2px solid black;
  margin: 0.3em
  transition: all 2s ease;
}
var btn = document.querySelector('input');
btn.addEventListener('click', updateBtn);

function updateBtn() {
    $el = $("<div>", {
            id: 'middle-item',
            text: "New element"
        });
    $("#middle").append($el);
}

How to make the #three element move smoothly when you click on the button?


Solution

  • You can do it with animate() function.

    var btn = document.querySelector("input");
    btn.addEventListener("click", updateBtn);
    
    function updateBtn() {
      $el = $("<div>", {
        id: "middle-item",
        text: "New element",
        style: "display: none"
      });
      $("#middle")
        .append($el)
        .animate({ height: "+=" + $el.height() }, 200, function() {
          $el.fadeIn(100);
        });
    }
    /* You don't need to define a `css transition` anymore. */
    #top, #middle, #bottom {
      font-size: 1.5em;
      border: 2px solid black;
      margin: 0.3em
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="top">
      Top of the page
    </div>
    
    <div id="middle">
    
    </div>
    
    <div id="bottom">
      <form>
        <input type="button" value="Add an element">
      </form>
      End of the page
    </div>