Home > database >  CSS transition does not animate on toggle
CSS transition does not animate on toggle

Time:09-04

I made a little accordion that I would like to animate. I have the following code but the animation as written is not working and I don't know why.

I know it's somehow complicated to make the height to work, but I managed to find a work around using max-height.

I would like my div to have an animated width and height to make it feel like you unfold it.

The weird behaviour is that if you resize the window, everything seems animated...

document.getElementById("ping").onclick = function () {
  console.log(this);
  this.children[1].classList.toggle("active");
};
.content.active {
  display: block;
  max-height: 200px;
  transition-property: width, max-height;
  transition-duration: 400ms, 100ms;
  transition-timing-function: cubic-bezier(0.305, 0, 0, 1.015);
  transition-delay: 400ms, 100ms;
  width: 40vw;
  background: orange;
}

.content {
  width: 0px;
  max-height: 0px;
  transition-property: width, max-height;
  transition-timing-function: cubic-bezier(0.305, 0.000, 0.000, 1.015);
  transition-duration: 400ms, 100ms;
  transition-delay: 100ms, 100ms;
  background: orange;
  display: none;
}

.cat.active {
  background: orange;
}
<section id="item0">

  <div id="ping" >
    <div  style="">
      <a>Open</a>

    </div>
    <div  style="">
      <div>
        <div >
          first test <br>
          another
        </div>
      </div>
    </div>
</section>

CodePudding user response:

1.) Only apply the transition parameters to the initial state, not to the .active state/class.

2.) Don't use display:none and block, but instead transition between max-height: 0 and width: 0 and their ".active" values.

3.) To hide the overflowing contents (which would still be visible), apply overflow: hidden to the initial state

document.getElementById("ping").onclick = function () {
  console.log(this);
  this.children[1].classList.toggle("active");
};
.content.active {
  max-height: 200px;
  width: 40vw;
}

.content {
  max-height: 0;
  width: 0px;
  transition-property: width, max-height;
  transition-duration: 400ms, 100ms;
  transition-timing-function: cubic-bezier(0.305, 0, 0, 1.015);
  transition-delay: 400ms, 100ms;
  background: orange;
  overflow: hidden;
}

.cat.active {
  background: orange;
}
<section id="item0">

  <div id="ping" >
    <div  style="">
      <a>Open</a>

    </div>
    <div  style="">
      <div>
        <div >
          first test <br>
          another
        </div>
      </div>
    </div>
</section>

  • Related