3

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%";
            });
        }
    });
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am going to mark your answer as acceptable as it solved the main problem. However, the const el = document.querySelectorAll(".aboutCollapsible"); doesn't work with the addEventListener as far as I can see.
you have to do a loop on the querySelectorAll() to addEventListener to each item

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.