


Creating a Dynamic Navigation Script for Active State and Expandable Menus
Nov 08, 2024 am 01:14 AMWhen building a dynamic web application, the user interface (UI) needs to offer an intuitive navigation experience. Whether it’s an e-commerce site with multiple product categories or a content-heavy admin dashboard, having active states and expandable menus enhances usability. In this blog post, we’ll walk through creating a JavaScript script that dynamically highlights the current page in the navigation and expands relevant sections based on the user's path.
The Problem
When users navigate through multi-layered menus, we want:
- An active state on the current page link.
- Expandable sections that open automatically if the user is on a page nested within a menu.
Let’s look at an example HTML structure and how to add JavaScript to make our menu smart.
Example Menu Structure
Here’s a typical nested menu structure. We’ll be working with menu-item for each item in the menu, menu-link for links, and menu-sub for collapsible submenus.
<!-- Categories --> <li> <p>In this structure:</p> <ul> <li>Each main menu link (menu-toggle) opens a submenu when clicked.</li> <li>The actual pages are in the submenu links (menu-link).</li> </ul> <h3> The JavaScript Solution </h3> <p>We’ll use JavaScript to:</p> <ol> <li>Identify the current page.</li> <li>Apply an active class to the link that matches the current URL.</li> <li>Add an open class to the parent menu if the link is inside a collapsed submenu.</li> </ol> <p>Here’s the JavaScript code:<br> </p> <pre class="brush:php;toolbar:false"><script> window.onload = function () { const currentPath = window.location.pathname; // Get the current path const links = document.querySelectorAll('.menu-link'); // Select all menu links links.forEach(function (link) { // Check if the link's href matches the current page's path if (link.getAttribute('href') === currentPath) { // Add 'active' class to the parent 'li' element of the link const menuItem = link.closest('.menu-item'); if (menuItem) { menuItem.classList.add('active'); // Check if the link is within a 'menu-sub', expand the parent menu const parentMenu = menuItem.closest('.menu-sub'); if (parentMenu) { // Add 'open' class to the parent 'menu-item' of the submenu const parentMenuItem = parentMenu.closest('.menu-item'); if (parentMenuItem) { parentMenuItem.classList.add('open'); } } } } }); }; </script>
Breaking Down the Code
- Get the Current Path:
const currentPath = window.location.pathname;
This grabs the path of the current page (e.g., /inventory-issues), which we’ll use to compare with the href of each link in the menu.
- Select Menu Links:
const links = document.querySelectorAll('.menu-link');
We select all elements with the class menu-link, assuming these contain links to various sections of the site.
- Matching the Current Page:
if (link.getAttribute('href') === currentPath) {
For each link, we check if its href matches the currentPath. If it does, that link is for the current page.
- Setting Active State:
menuItem.classList.add('active');
We add an active class to the closest menu-item, allowing us to style the active page link.
- Expanding the Parent Menu:
const parentMenuItem = parentMenu.closest('.menu-item'); parentMenuItem.classList.add('open');
If the active link is within a submenu (menu-sub), this part of the code finds the parent menu-item containing that submenu and adds the open class, expanding it.
Adding CSS for Active and Open States
You’ll want to define styles for the active and open classes in your CSS:
<!-- Categories --> <li> <p>In this structure:</p> <ul> <li>Each main menu link (menu-toggle) opens a submenu when clicked.</li> <li>The actual pages are in the submenu links (menu-link).</li> </ul> <h3> The JavaScript Solution </h3> <p>We’ll use JavaScript to:</p> <ol> <li>Identify the current page.</li> <li>Apply an active class to the link that matches the current URL.</li> <li>Add an open class to the parent menu if the link is inside a collapsed submenu.</li> </ol> <p>Here’s the JavaScript code:<br> </p> <pre class="brush:php;toolbar:false"><script> window.onload = function () { const currentPath = window.location.pathname; // Get the current path const links = document.querySelectorAll('.menu-link'); // Select all menu links links.forEach(function (link) { // Check if the link's href matches the current page's path if (link.getAttribute('href') === currentPath) { // Add 'active' class to the parent 'li' element of the link const menuItem = link.closest('.menu-item'); if (menuItem) { menuItem.classList.add('active'); // Check if the link is within a 'menu-sub', expand the parent menu const parentMenu = menuItem.closest('.menu-sub'); if (parentMenu) { // Add 'open' class to the parent 'menu-item' of the submenu const parentMenuItem = parentMenu.closest('.menu-item'); if (parentMenuItem) { parentMenuItem.classList.add('open'); } } } } }); }; </script>
Benefits of this Approach
- Automatic Active State: No need for hardcoding the active link on every page. This script updates the active link dynamically.
- Expandable Menus: Users see only the sections relevant to their current page, reducing the need to manually open menus.
- Reusable: This script is generic enough to work with various nested menu structures, making it adaptable to multiple types of sites.
? from eddiegulay
The above is the detailed content of Creating a Dynamic Navigation Script for Active State and Expandable Menus. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.
