Transition The Size of a Container When jQuery Adds Children

Viewed 42

I'm looking for a way to animate the increase of an element's (border) size when jQuery either adds a child or shows one that was hidden, either or. This JSFiddle likely explains this better. Instead of the divider instantly transforming to the new size when the label is clicked displaying the second label, is there a way to transform it slowly? I've tried every combination of CSS and JS I could think of and find on Stack to no avail. Help appreciated!

function load() {
  $("#example").hide();
  $("label").click(function() {
    $("#example").fadeIn();
  })
}
div {
  display: grid;
  grid-template-columns: 1fr;
  border: 1px solid black;
  font-size: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body onload=load()>
  <div>
    <label>Shown</label>
    <label id=example>Addition</label>
  </div>
</body>

2 Answers

You could use .slideToggle() - this will slide the bottom border down as the parent div increases in size.

$("#example").slideToggle();

This will also bring the bottom border up in a smooth transition when hiding.


function load() {
        $("#example").hide();
    $("label").click(function() {
            $("#example").slideToggle();
    })
}
div {
    display: grid;
    grid-template-columns: 1fr;
    border: 1px solid black;
    font-size: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload=load()>
  <div>
      <label>Shown</label>
      <label id=example>Addition</label>
  </div>
</body>

In the case that you are looking to delay the showing of the actual element and its properties (border), you can add a setTimeout() function to the JS code that will delay for a given amount of time as set in your timeout function, then it will run the built in fadeIn jQuery function.

You could add a CSS animation and use @keyframes to make the animations opacity fade in, however this will be constrained to certain properties in CSS only.

Let me know if this was not what you were looking to achieve. I used the example code you linked to in the JSFiddle.

function delayFade(time) {
  setTimeout(() => $("#example").fadeIn(), time);
}

function load() {
  $("#example").hide();
  $("label").click(() => delayFade(1500));
}
div {
  display: grid;
  grid-template-columns: 1fr;
  border: 1px solid black;
  font-size: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body onload=load()>
  <div>
    <label>Shown</label>
    <label id=example>Addition</label>
  </div>
</body>

Related