0

I have this cart that contains .cartItem children, with their CSS below :

.cartItemsContainer {
    overflow: auto;
    overflow-x: hidden;
    padding: 10px;
    transition: all .4s ease;
}

.cartItem {
    display: inline-block;
    position: relative;
    width: 100%;
    padding: 4px;
    transition: all .4s ease;
}

.cartItemSlide {
    padding-left: 350px;
    opacity: 0;
}

I have this Javascript code that is executed when I delete a cart item :

// make it disappear with a CSS transition, then delete it when out of sight
cartItem.classList.add('cartItemSlide');
onTransitionEnd(cartItem, 'padding-left', () => 
{
    cartItem.parentNode.removeChild(cartItem);
});

So I have my cart item that slides to the right, and is then deleted when this transition is over. The problem is that when the cart item is removed from the DOM, there is no height transition for my cartItemsContainer

I want the parent height to be smoothly reduced when its child is removed, how can I achieve this ?

Fumée Noire
  • 93
  • 1
  • 8
  • You can't animate `height` when height value is `auto`, you have to set two explicit heights. That's the CSS "issue", look through the [How can I transition height: 0; to height: auto; using CSS?](https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css) – brynzovskii Oct 08 '19 at 09:07

1 Answers1

1

I did a quick possible solution, you can adjust it to your need:

var div = document.getElementById('div');
var p = document.getElementsByClassName('p');

for(var i = 0; i < p.length; i++) {
  p[i].addEventListener("click", function(e) {
    myFunc(e);
  });
}

function myFunc(e) {
  e.target.innerHTML = '';
  e.target.style.maxHeight = '0px';
  e.target.style.padding = '0';
}
div {
  outline : 1px solid red;
  padding: 10px;
}

p {
  padding: 10px;
  max-height: 100px;
  background: #000;
  color: #fff;
  transition: all 0.2s linear;
}
<div id=div class=div>
  <p class=p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint laboriosam itaque dolore aspernatur labore, blanditiis nesciunt sapiente architecto veniam quo culpa, quibusdam beatae dolorem esse dignissimos commodi, distinctio laborum perferendis.</p>
  <p class=p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Pariatur id exercitationem magni esse non, perferendis, nemo doloremque impedit eos nobis in distinctio sunt tempora laudantium? Veniam aliquid ex nemo quod!</p>
</div>

Try to click on p element to see the animation.

brynzovskii
  • 355
  • 4
  • 13
  • You can note that I am forced to use `max-height` value set in px as `auto` and `100%` values can not be animated. – brynzovskii Oct 08 '19 at 09:29