I’m in the process of designing a website. I want a couple of containers to be hidden when the page is first loaded which can then be displayed with certain buttons.
I am trying to put this into code the following way:
// Function to toggle visibility
function toggleVisibility() {
var container = document.getElementById("your-container-id");
// Toggle the visibility classes
if (container.classList.contains("hidden-section")) {
container.classList.remove("hidden-section");
container.classList.add("visible-section");
// Trigger a reflow
void container.offsetWidth;
} else {
container.classList.remove("visible-section");
container.classList.add("hidden-section");
}
}
// Find the button and attach the click event handler
document.addEventListener("DOMContentLoaded", function() {
var button = document.querySelector('#myButton');
button.addEventListener('click', toggleVisibility);
});
.hidden-section {
display: none;
}
.visible-section {
display: flex;
}
While the button to trigger the change of visibility has the CSS id #myButton
and the respective container the CSS id #your-container-id
.
When I have the container to be displayed when the page is initially loaded everything works as expected.
However, when the container get assigned the .hidden-section
class upon the initial load, some of the content is not being display. When I resize my browser windows it appears though. So it somehow has to do something with calculating the size of the container.
Can anyone give me further hints how to fix this?
2
Answers
OK, I am rather new to stack overflow and trying to adjust to the good practices here. So I hope I can clear things up a bit by posting my entire HTML (it seems that I can't edit my original post anymore):
The container I want to toggle contains a photo gallery that is not being displayed.
I would really appreciate your help as I am really at the end of my wisdom
This is useless…
Just place your JS in the <script> section of your document, and you should be OK…
In case you’re wondering, DOMContentLoaded is a premature state of document loading that one can use to take performance measurements of a website as an example, but it’s of no use to your needs.
If you must auto-trigger something use this event instead…
Meaning, you could’ve done this instead: