简体   繁体   中英

Run code after CSS transition has finished with pure JavaScript

I am trying to wrap my head around transitionend events but I can't get them to work.

Essentially what I want to do is to run content.style.maxHeight = 100% after a transition has finished.

The two problems that I have run into are:

  1. The code will run on both the if and else statement.
  2. Doesn't work on more than the first class named: .aboutCollapsible

CSS Class:

.aboutCollapsible {
    font: 16px/24px "Roboto";
    background: #202020;
    text-align: justify;
    margin-bottom: 20px;
    width: 580px;
    max-width: 100%;
    padding: 1px 20px 5px 20px;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.5s ease;
}

JavaScript

// Collapsible
var coll = document.getElementsByClassName("collapsible");
const el = document.querySelector(".aboutCollapsible");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function () {
        this.classList.toggle("active");
        var content = this.nextElementSibling
        if (content.style.maxHeight) {
            content.style.maxHeight = null;
        } else {
            content.style.maxHeight = content.scrollHeight + "px";
            el.addEventListener("transitionend", function () {
                content.style.maxHeight = "100%";
            });
        }
    });
}

I didn't run your code but just by reading it I could have some clues for you.

1.The code will run on both the if and else statement.

You should try something like

if (content.style.maxHeight == '100%')

2.Doesn't work on more than the first class named: .aboutCollapsible

You should use

const el = document.querySelectorAll(".aboutCollapsible");

instead of just the simple querySelector that only returns the first element . And then loop on the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM