I am trying to get an overlay menu effect on my site using JS, but it only works on either the mobile or desktop. Never on both simultanously. I am editing the code in the custom liquid spaces.
I have tried to strip down the code to ONLY the code for the menu, to make it simple but no success. I have tried to give the menu different names for mobile and desktop, to minimize the risk for conflict but that doesnt seem to matter at all, still only works on one or the other, not both.
Right now it works on the desktop view, while the menu-button on the mobile-view render nothing.
here’s how you can handle your overlay menu to ensure it works both on desktop and mobile views.
Ensure Correct CSS with Media Queries:
/* Desktop-specific styles */
@media (min-width: 750px) {
.overlay-menu {
display: none; /* Start with hidden */
}
.menu-open {
display: block; /* Show the overlay when menu is open */
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.8);
z-index: 1000;
}
}
/* Mobile-specific styles */
@media (max-width: 749px) {
.overlay-menu {
display: none; /* Start hidden on mobile */
}
.menu-open {
display: block; /* Show menu when open on mobile */
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.8);
z-index: 1000;
}
}
JavaScript to Handle Both Views:
document.addEventListener("DOMContentLoaded", function () {
const menuButtonDesktop = document.querySelector('.menu-button-desktop');
const menuButtonMobile = document.querySelector('.menu-button-mobile');
const overlayMenu = document.querySelector('.overlay-menu');
function toggleMenu() {
overlayMenu.classList.toggle('menu-open');
}
// Desktop menu button listener
if (menuButtonDesktop) {
menuButtonDesktop.addEventListener('click', function () {
toggleMenu();
});
}
// Mobile menu button listener
if (menuButtonMobile) {
menuButtonMobile.addEventListener('click', function () {
toggleMenu();
});
}
});
Verify with Refresh Theme Customizations:
document.addEventListener("DOMContentLoaded", function () {
const menuButton = document.querySelector('.menu-button'); // Single button for both
const overlayMenu = document.querySelector('.overlay-menu');
function toggleMenu() {
overlayMenu.classList.toggle('menu-open');
}
// Event listener for both mobile and desktop menus
if (menuButton) {
menuButton.addEventListener('click', function () {
toggleMenu();
});
}
});
I have checked the theme console, and noticed that the JavaScript display the menu for both desktop and mobile is breaking due to the jQuery script not being loaded. You can see the console error in the screenshot below.
Okay so if i understand it right, its some kind of conflict with the javascript? That is the feeling ive been having but i dont really know if it is a development-bug or just me who isnt applying the scripts correctly?