I have multiple toggles being called at the same time during a click /eventListener and it works but I'm wondering if there is a cleaner way to write the code where it doesn't look so repetitive.
Here is a snippet of the code I'm trying to refactor/clean up. Any help or point in the right direction is greatly appreciated. Thanks!
document.getElementById("menu-toggle").addEventListener("click", mobileMenuToggle);
function mobileMenuToggle() {
var hideMenu = document.getElementById("mobile-menu-container");
hideMenu.classList.toggle("hide-menu");
var hideMenuIcon = document.getElementById("menu-toggle");
hideMenuIcon.classList.toggle("hide-menu-icon");
var closeMenuIcon = document.getElementById("close-menu-toggle");
closeMenuIcon.classList.toggle("show-close-icon");
var closeMenuIcon = document.getElementById("container-bg-toggle");
closeMenuIcon.classList.toggle("show-icon-bg");
}
Few other options
To make it more concise, you can get rid of references, which you are not reusing
function mobileMenuToggle() {
document.getElementById("mobile-menu-container").classList.toggle("hide-menu");
document.getElementById("menu-toggle").classList.toggle("hide-menu-icon");
document.getElementById("close-menu-toggle").classList.toggle("show-close-icon");
document.getElementById("container-bg-toggle").classList.toggle("show-icon-bg");
}
In case if these elements are nested, You can just write a css rule and do one toggle
#mobile-menu-container.hide-menu .menu-toggle {
display:none;
}
#mobile-menu-container.hide-menu .close-menu-toggle {
display:block;
}
And you can just toggle the parent container alone
function mobileMenuToggle() {
document.getElementById("mobile-menu-container").classList.toggle("hide-menu");
}
In case if you are using jquery, you can use the jquery toggle, which is bit short
$('#mobile-menu-container').toggleClass('hide-menu');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With