Currently working on enhancing the navigation menu of my website, and I have encountered a challenge with a dropdown sub-menu when viewed on mobile devices. In reference to w3Schools, I successfully implemented a hover-based sub-menu for desktop users.
However, two issues persist on mobile:
- The primary concern is enabling a clickable functionality to open the menu. I attempted to find solutions for creating a toggle that works via click on mobile and hover on desktop, but lacking expertise in JavaScript makes it challenging. While experimenting with making the menu accessible through clicking both on desktop and mobile, I prefer maintaining the hover feature for desktop users.
- Additionally, I aim to customize the menu display for mobile and tablet views. Rather than displaying as a popup like on desktop, I envision a block layout spanning the width of a popout sidebar. My attempts to style the menu differently resulted in an accordion-like dropdown, overlaying other list items instead of pushing them down.
Your assistance in addressing these issues would be greatly appreciated!
Here's the code snippet including a click-triggered menu for both desktop and mobile:
// Code for toggling between showing/hiding the dropdown content upon user clicks
function subOpen() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if clicked outside
window.onclick = function(event) {
if (!event.target.matches('.sub-menu-link')) {
var dropdowns = document.getElementsByClassName("sub-menu-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
//Code for hamburger menu toggle
const menuBtn = document.querySelector(".menu-btn");
let menuOpen = !1;
menuBtn.addEventListener("click", () => {
menuOpen ? (menuBtn.classList.remove("open"), menuOpen = !1, document.documentElement.style.overflow = "scroll", document.body.scroll = "yes") : (menuBtn.classList.add("open"), menuOpen = !0, document.documentElement.style.overflow = "hidden", document.body.scroll = "no")
})
...