I have a button that should hidden area with nice animation. It's using height attribute to make the animation.
The issue is, when I add content to the "hiddenable" area, the content isn't viewable as it's outside the given height. And I have to clic again on "Open" to re-hide and re-open the area.
Here is a MRE :
function changeVisility(all, toCancel = null) {
if(toCancel != null)
toCancel.preventDefault();
if(!(Symbol.iterator in Object(all)))
all = [ all ];
for(var div of all) {
for(const wrapper of div.querySelectorAll(".collapse-wrapper")) {
if(wrapper.style.height == '0px') {
wrapper.style.height = wrapper.querySelector(".collapse-content").getBoundingClientRect().height + `px`;
} else {
wrapper.style.height = '0px';
}
}
}
}
for(const wrapper of document.querySelectorAll(".collapse-wrapper")) {
if(wrapper.style.height != '0px') { // set real height
wrapper.style.height = wrapper.querySelector(".collapse-content").getBoundingClientRect().height + `px`;
} else
wrapper.style.height = '0px';
}
function addContent() {
document.getElementById("contentToAdd").insertAdjacentHTML("beforeend", "<p>Other text</p>");
}
.collapse-wrapper {
overflow: hidden;
transition: height 300ms ease-in;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<body style="margin-left: 10px;">
<div class="form-check" style="padding-top: 0.5rem;">
<input class="form-check-input" type="checkbox" name="newinput" id="newinput" onchange="changeVisility(document.getElementById('input_selection'));">
<label class="form-check-label" for="newinput">
Open
</label>
</div>
<div id="input_selection">
<div style="height: 0px;" class="collapse-wrapper">
<div class="collapse-content row" id="contentToAdd" style="background-color: red;">
<button onclick="addContent()" type="button" class="btn btn-primary">Add</button>
<p>Some text</p>
</div>
</div>
</div>
</body>
To reproduce :
- Clic on "Open" to open the area
- Clic on "Add" - Nothing show (but the text is well added to HTML)
- Clic on "Open" twice (to hide then re-open)
- See the red area upgrade with "Other text" showed
How can I make them be showable and keeping the nice animation ?
I tried to set height to null to show, but there is no longer animation...
.collapse-content, and assign that as the new height for the.collapse-wrapper..collapse-content, not specially for the added content