I'm using the following JavaScript code to toggle between 0 height and X height. It's the dropdown menu for a hamburger icon.
// Hamburger navigation
const menuToggle = document.querySelector(".menu-toggle");
const nav = menuToggle.parentElement;
const menuDropdown = document.querySelector(".menu-dropdown");
menuToggle.addEventListener("click", event => {
event.preventDefault();
nav.classList.toggle("is-open");
const height = menuDropdown.scrollHeight;
if (nav.classList.contains("is-open")) {
menuDropdown.style.setProperty("height", height + "px");
} else {
menuDropdown.style.setProperty("height", "0");
}
});
I can do the toggling of the class "is-open" using something like this in React and it works:
const [isOpen, setState] = useState(false)
const toggleNav = () => setState(!isOpen)
But how do I handle the height?
const height = menuDropdown.scrollHeight;
if (nav.classList.contains("is-open")) {
menuDropdown.style.setProperty("height", height + "px");
} else {
menuDropdown.style.setProperty("height", "0");
}
I would be grateful for any suggestion.