CSS Javascipt Minimal Code for Menu
CSS Javascript Menu with Minimal Amount of CSS and Javascript Code Required to Create Menu.
Home
Short:
Menu 1
Option Number 1
Option Number 2
Sub Menu 2
Menu 2
Sub Menu 2
Change Menu Backcolor
Sub Menu 3
The CSS code for the menu
/* the blue, screen width strip */ .menustrip { background-color:#9bc; width:100%; } /* the menu link text that when clicked, opens the menu */ .menu { display:inline-block; /* menu link text side by side */ padding:5px 10px; /* spacing between menu link text */ position:relative; } /* make the menu text look like a link */ .menu span { color:blue; cursor:pointer; text-decoration:underline; } /* the submenu is a list ul */ ul.submenu { background-color:white; border:1px solid #ddd; box-shadow:rgba(50, 50, 93, 0.25)0px 6px 12px -2px; display:none; list-style-type:none; margin:5px; padding:5px; position:absolute; } /* each individual menu item */ .submenu li { cursor:pointer; padding:5px; white-space:nowrap; /* dont allow menu text to wrap */ } /* nice line between menu items */ .submenu li:not(:last-child) { border-bottom:1px inset #ddd; } /* on menu item mouseover, background color */ .submenu li:hover { background-color:#9bc; }
The HTML code for the menu
Menu 1
Option Number 1
Option Number 2
Sub Menu 2
Menu 2
Sub Menu 2
Change Menu Backcolor
Sub Menu 3
The JAVASCRIPT code for the menu
<script> // the menu link text that when clicked, opens the menu const menus = document.querySelectorAll(".menu"); // loop through each of the menu link text menus.forEach(menu => { // the menu themselves const submenu = menu.querySelector(".submenu"); // Show submenu when the menu on click if hidden, if already showing, hide menu.addEventListener("click", () => { submenu.style.display = (submenu.style.display === "block") ? "none" : "block"; }); // hide submenu when clicking outside the menu document.addEventListener("click", (e) => { // if click happens outside the menu, hide submenu if (!menu.contains(e.target)) { submenu.style.display = "none"; } }); // Prevent submenu from disappearing when clicked inside submenu.addEventListener("click", (e) => { e.stopPropagation(); }); // Select all child elements of
inside the .submenu (the select and color picker) const liChildren = document.querySelectorAll(".submenu li > *"); // prevent the interacting with any controls on the menu from hiding the menu liChildren.forEach(child => { child.addEventListener("click", (e) => { e.stopPropagation(); }); }); }); // this script code is only for changing backcolor of menu on hover function changeBackcolor() { const arrMenuLI = document.querySelectorAll(".submenu li"), colorPicker = document.querySelector("#colorPicker"); arrMenuLI.forEach(li => { li.addEventListener("mouseenter", () => { li.style.backgroundColor = colorPicker.value; }); li.addEventListener("mouseleave", () => { li.style.backgroundColor = '#fff'; }); }); alert("Menu backcolor is now " + colorPicker.value); } </script>
source code home