Ways to create a smooth transition in element height without a known fixed target height

Is it possible to create a smooth height transition for an element when the target height is unknown?

Replacing height: unset with height: 100px allows the animation to work, but this presents a problem as the height needs to be based on content and may vary for different elements.

Similarly, using max-height rather than height requires a hardcoded value (e.g. 1000px) which means that for a shorter item, there may be a delay before the animation begins.

$('.c').change(function() {
    for(var i = 1; i <= 3; i++) {
        var item = $('#item' + i)
        if($('#c' + i).prop('checked')) item.addClass('show')
        else item.removeClass('show')
    }
})
.item {
    border: 1px solid red;
    position: relative;
    overflow: hidden;
    height: 0;
    transition: all 1s;
}
.item.show {
    height: unset;
    transition: all 1s;
}
<div>
    <input type="checkbox" class="c" id="c1" checked />
    <input type="checkbox" class="c" id="c2" />
    <input type="checkbox" class="c" id="c3" checked />
</div>
<div class="items">
    <div id="item1" class="item show">
        <h3>Lorem ipsum</h3>
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    <div id="item2" class="item">
        <h3>Lorem ipsum</h3>
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
    </div>
    <div id="item3" class="item show">
        <h3>Lorem ipsum</h3>
        Lorem ipsum dolor sit amet.
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №1

To adjust the element's size, consider setting its height attribute to match its scrollHeight.

Here is a jQuery solution:

$('.c').change(function() {
  const c = $(this);
  const item = $(c.attr('rel'));
  item.css({
    height: item[0].scrollHeight * c.prop('checked')
  })
})
.item {
  border: 1px solid red;
  position: relative;
  overflow: hidden;
  height: 0;
  transition: all 1s;
}
<div>
  <input type="checkbox" class="c" rel="#item1" />
  <input type="checkbox" class="c" rel="#item2" />
  <input type="checkbox" class="c" rel="#item3" />
</div>
<div class="items">
  <div id="item1" class="item">
    <h3>Lorem ipsum</h3>
    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="item2" class="item">
    <h3>Lorem ipsum</h3>
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
  </div>
  <div id="item3" class="item">
    <h3>Lorem ipsum</h3>
    Lorem ipsum dolor sit amet.
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to shift an image within a div using CSS?

I am currently facing a challenge with moving an image inside a div element. I need to adjust the image by 50 pixels down and 50 pixels left, but I'm having difficulty figuring out how to do this in CSS. I am struggling to find the correct code to con ...

modifying the href attribute of a tag is determined by the value of window

I'm working on a jQuery snippet that detects the current window's URL and, depending on the href value of the window, changes the href of an anchor tag. Here's what my code looks like so far: (function($) { "use strict"; $(document).re ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Using jQuery to perform global search and replace with a variable

In this scenario, I am attempting to substitute every occurrence of the newname variable with a hyphen (-). However, in my specific case, newname is being interpreted as text instead of a variable. var newname = 'test'; var lastname = $(this).a ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

Prevent displaying page confirmation prompts when a user clicks on hyperlinks

One way to display a confirmation message when a user tries to leave the current page is by using this method: window.addEventListener("beforeunload", function (e) { var confirmationMessage = "Are you sure you want to leave?"; ...

Is it possible to load asynchronous JS and then execute functions?

Is there a way to make my script behave like the Google Analytics JavaScript snippet? Here is an example of what I have: (function(d, t) { var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.src = 'myjs.js'; s.par ...

What is the best way to execute a function before showing an alert in a $.post() callback?

Just to clarify, the code I'm working with is not original to me; I am simply making some interface adjustments using a plugin for an existing system. The task at hand involves creating a plugin that utilizes blockUI (yes, a plugin within a plugin) t ...

Adjusting the width of the final card in the deck grid

Currently, I am utilizing angular-deckgrid for image display purposes. Within a container, there are two columns in which images are displayed with the column-1-2 class according to the documentation. However, in certain scenarios where only one image is p ...

Attempting to utilize Vue js to connect to an API

I'm currently facing difficulties while trying to access an API in order to retrieve data. As a novice in the world of vue.js and javascript, I encountered an error message saying Uncaught SyntaxError: Invalid shorthand property initializer. Unfortuna ...

What strategies can be used to stop elements from reverting to their original state?

Hey there, I'm currently experimenting with animation and trying to create a cool two-step effect: 1. elements falling down and 2. pulsating on click. However, I've run into an issue where after the clicking action, the elements return to their o ...

Node.js local storage/cookie functionality

Running three different apps on Node.js at ports 3000, 3005, and 3007. I need to set a LocalStorage or Cookie variable at port 3000 and access it from the apps running at ports 3005 and 3007. Folder structure: nodep/ |-app.js (runs at port 30 ...

Get rid of empty spaces in gridstack js

My latest project involves using gridstack js In the image displayed, I have highlighted the excess white space (in blue) that needs to be removed. Take a look at this visual: Any suggestions on how to eliminate this unwanted white space? ...

What is the best way to retrieve the value from a textfield in one module and use it in a

How can I access the value of a textField in another module within React.js without importing the entire textfield component? What is the most effective approach to get access to the value variable in a different module? Below is a sample functional textF ...

What is the best way to ensure a div container fills the entire height of the screen?

I am currently working on developing my very first iOS HTML5 app, which is a simple quote application. One challenge I am facing is how to set the height of my container div to match that of an iPhone screen. You can view the design I have so far on this j ...

The format for a DateTime field in a JSON string array is as follows: yyyy-MM-dd hh:mm:ss

I am working with a JSON array string pulled from a database and I need to format the DateAndTime field into yyyy-MM-dd hh:mm:ss. This formatting needs to be flexible as the data passed through will vary, except for the DateAndTime. Here is my current att ...

Transform a JavaScript Array into a JSON entity

Currently working on a Mail Merge project using Google Apps Script, I've encountered an issue with displaying inline images in the email body. After sending the email using GmailApp.sendEmail(), all inline images are shown as attachments instead of be ...

Use selenium to locate an element based on its CSS selector

Looking to extract user information from each block using the following code snippet: driver.get("https://www.facebook.com/public/karim-pathan") wait = WebDriverWait(driver, 10) li_link = [] for s in driver.find_elements_by_class_name('clear ...

Populate HTML form with return values using jQuery AJAX

I am struggling with retrieving values from jQuery/AJAX and displaying them in an HTML form within the index.php file. This is what my index.php looks like: <script type="text/javascript"> $(document).ready(function () { $('#display'). ...

d3.json is unable to parse a value of 'Infinity

My goal is to retrieve data from an SQLite database and convert it into JSON format for use with d3.js in order to create a graph. I have successfully obtained this data in JSON format using the following URL: http://localhost:8085/SQLQuery/?date1=2019-03 ...