Animating the size of an element with dynamic content

I am working on a feature where clicking on a card should display a summary.

When a new summary is shown, I want the summary container to animate and align its position with the associated card (top).

However, despite my efforts, I am facing an issue where the height of the summary container 'snaps' without any smooth transition.

*Solution Attempt 1

$('.summary > div').css({'height':0,'overflow':'hidden'});
$('.summary > div[data-content="'+ activeIndex +'"]').css({'height':'initial'});

*Solution Attempt 2

$('.summary > div').fadeOut();
$('.summary > div[data-content="'+ activeIndex +'"]').fadeIn();

*Solution Attempt 3

$('.summary > div').animate({'height':0, 'overflow':'hidden'});
$('.summary > div[data-content="'+ activeIndex +'']).animate({height:'initial', 'overflow':'visible'},200);

In addition to that, in my CSS code, I have added transition: all 2s ease; to animate both margin-top and height properties.

To better understand this functionality, I have provided a test case below:

$(document).ready(function() {
  alignSummary = function() {
    // Animate the summary panel
    $('.summary').css({
      'margin-top': ($('.card.is-active')[0].offsetTop - 50)
    })

    // Show/hide the relevant summary content
    var activeIndex = $('.card.is-active').index();
    $('.summary > div').hide();
    $('.summary > div[data-content="' + activeIndex + '"]').show();
  }
  alignSummary();
});

$('.card').on('click', function() {
  // Do this if a card with a greater index is clicked
  if ($(this).closest('.card').index() > $('.card.is-active').index()) {
    // Scroll the window to the top of the active card
    $([document.documentElement, document.body]).animate({
      scrollTop: ($(this).closest('.card').offset().top - 20)
    }, 800);
  }

  // Swap the active class to the card clicked
  $(this).closest('.card').siblings().removeClass('is-active');
  $(this).closest('.card').addClass('is-active');
  alignSummary();
})
body {
  margin: 0;
}

.container {
  padding: 25px;
  overflow: hidden;
}

.card,
.summary {
  margin-bottom: 1rem;
  border: 1px solid #e3e3e3;
  padding: 1rem;
  border-radius: 4px;
  width: 49%;
}

.card.is-active {
  border-color: red;
}

.card {
  float: left;
}

.summary {
  float: right;
  width: 40%;
  transition: all 2s ease;
}

div[data-content="1"] {
  height: 500px;
}

div[data-content="2"] {
  height: 100px;
}

div[data-content="3"] {
  height: 400px;
}

div[data-content="4"] {
  height: 1200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="summary">
    <div data-content="1">
      <h2>Variable height summary 1</h2>
      <p>Some content: 500px height</p>
    </div>
    <div data-content="2">
      <h2>Variable height summary 2</h2>
      <p>Some content: 100px height</p>
    </div>
    <div data-content="3">
      <h2>Variable height summary 3</h2>
      <p>Some content: 400px height</p>
    </div>
    <div data-content="4">
      <h2>Variable height summary 4</h2>
      <p>Some content: 1200px height</p>
    </div>
  </div>
  <div class="card is-active">Click me</div>
  <div class="card">Click me</div>
  <div class="card">Click me</div>
  <div class="card">Click me</div>


</div>

Answer №1

Utilize jquery's .slideUp/.slideDown instead of .hide/.show for animating height.

$(document).ready(function() {
  alignSummary = function() {
    // Adjust the summary panel
    $('.summary').css({
      'margin-top': ($('.card.is-active')[0].offsetTop - 50)
    })

    // Toggle the relevant summary content
    var activeIndex = $('.card.is-active').index();
    $('.summary > div').slideUp(1000);
    $('.summary > div[data-content="' + activeIndex + '"]').slideDown(1000);
  }
  alignSummary();
});

$('.card').on('click', function() {
  // Perform this action when a card with a higher index is clicked
  if ($(this).closest('.card').index() > $('.card.is-active').index()) {
    // Scroll to the top of the active card
    $([document.documentElement, document.body]).animate({
      scrollTop: ($(this).closest('.card').offset().top - 20)
    }, 800);
  }

  // Change the active class to the clicked card
  $(this).closest('.card').siblings().removeClass('is-active');
  $(this).closest('.card').addClass('is-active');
  alignSummary();
})
body {
  margin: 0;
}

.container {
  padding: 25px;
  overflow: hidden;
}

.card,
.summary {
  margin-bottom: 1rem;
  border: 1px solid #e3e3e3;
  padding: 1rem;
  border-radius: 4px;
  width: 49%;
}

.card.is-active {
  border-color: red;
}

.card {
  float: left;
}

.summary {
  float: right;
  width: 40%;
  transition: all 2s ease;
}

div[data-content="1"] {
  height: 500px;
}
...
<div data-content="4"] {
  height: 1200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="summary">
    <div data-content="1">
      <h2>Variable height summary 1</h2>
      <p>Some content: 500px height</p>
    </div>
    <div data-content="2">
      <h2>Variable height summary 2</h2>
      <p>Some content: 100px height</p>
    </div>
    <div data-content="3">
      <h2>Variable height summary 3</h2>
      <p>Some content: 400px height</p>
    </div>
    <div data-content="4">
      <h2>Variable height summary 4</h2>
      <p>Some content: 1200px height</p>
    </div>
  </div>
  <div class="card is-active">Click me</div>
  <div class="card">Click me</div>
  <div class="card">Click me</div>
  <div class="card">Click me</div>


</div>

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

Using values from a select menu in a math calculation without including a decimal point

I am working with a dropdown menu that contains various values... <select id="number1a" onChange="Addition()"> <option value="0" selected>-</option> <option value="10">10</option> <option value="7.5">7.5</optio ...

Using JavaScript, what is the method for inputting values into a window.prompt()?

I've been working on a project that involves scraping basic HTML pages from an internal server at my workplace. When I visit these pages, a popup window similar to a windows.prompt() appears, asking for a username and password with the message "Enter ...

Setting both 'a' and 'href' attributes to an existing list: best practices

I am struggling with updating my navigation bar so that the first item becomes a clickable link instead of just a list item. I attempted to add a link to the existing list item, but I think I should be using the .setAttribute method in order to achieve t ...

Zooming in on the background with an animated effect

I'm experimenting with a zoom in animation on a background image for a brief moment. It seems to work initially but then resets itself. To see an example, I've created a jsfiddle link: https://jsfiddle.net/onlinesolution/tk6rcLdx/ Any idea what ...

Switch between classes with a single click using jQuery and remember the previous state

My goal is to combine solutions from three different stackoverflow questions: Save current state after jquery click function, Save data to local storage, and HTML5 local storage save .toggleClass. I am attempting to toggle between two classes using an oncl ...

"Developing CSS styles that work seamlessly across all

What methods do professional web designers use to develop cross-browser compatible CSS? Is it typically a manual process, or are there specific toolkits available to simplify the task similar to YUI for JavaScript? I am looking to avoid WYSIWYG editors s ...

Flexbox's bootstrap columns display issue on smaller screens with no wrapping

I am currently working on a section of my website where I have applied some CSS to 2 divs and an anchor tag in order to center the content vertically. However, I am facing an issue with the flex style properties when the window size is less than 768px. In ...

Is it feasible to have multiple versions of React coexisting in a monorepo?

I have a monorepo set up with npm workspaces: ├─ lib │ └─ Foo └─ src ├─ App └─ Web I am looking to upgrade the Web package to React 18 while keeping App on React 17 My current dependencies are as follows: ├─ lib │ └ ...

Error with setting innerHTML property of a null nested div

This issue arises when the element is referenced before the DOM has completely loaded. To combat this, I have ensured that the necessary script runs only after the window has finished loading. Interestingly, if the getElementById() call is for a standalon ...

Rendering of @font-face on Windows 7 was executed flawlessly

I have been utilizing @font-face to implement custom fonts on a website. The custom font displays correctly in Firefox, IE, Safari, and Chrome on Mac. However, when viewed on Chrome in Windows 7, the text appears green at 10px instead of black or grey. ... ...

Trigger the running of a python script by clicking a button

On my HTML page, there is a single button that is supposed to trigger the execution of a python script upon being clicked. The goal is to receive the result of the script and display it on the same HTML page. The process involves validating the return val ...

jQuery append reduces size

Are there any tips to improve efficiency and clarity when using .append? For example: $('body').append("<div class='overlay'></div>"); // Standard way $('body').append("div.overlay"); // Is this alternative bette ...

Updating documents in a mongoDB collection can be done by simply

I require an update to my database that will modify existing data, as illustrated below: existing data => [{_id:"abnc214124",name:"mustafa",age:12,etc...}, {_id:"abnc21412432",name:"mustafa1",age:32,etc...}, {_id ...

What's the deal with eval() function?

There has been a lot of talk about the dangers of using the eval() function in HTML/JavaScript programming. While I want to pass in a string to have it read as a variable name, I am aware of the risks associated with using eval(). It seems like the functio ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Ways to prevent background replacement in CSS

Recently I came across this snippet of code: .active { background-color: black; color: white; } span { margin: 10px; } a { text-decoration: none; } .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .tabButton { margi ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

I cannot locate the dropdown list anywhere

As a beginner in html and css, I decided to follow a tutorial on youtube. The tutorial focuses on creating a navigation bar with dropdown menus using html and css. I wanted the names Ria, Kezia, and Gelia to be displayed when hovering my mouse over the Su ...

JavaScript does not function properly on dynamically loaded content from AJAX requests and it is not relying on

I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex. KaTeX GitHub Inside math.php, I include the Katex library from the CDN mentioned in the link above. The HTML ...

What is the most efficient way to evenly separate a CSS3 gradient?

Is there anyone who can assist me in achieving an even gradient break? body { height: 2500px; background: -webkit-linear-gradient(#000000 1%,#FFFFFF 1%,#FFFFFF 13%,#2ecc71 13%,#2ecc71 30%,#3498db 30%,#000000,#FFFFFF,#34495e); } I've been att ...