JavaScript realizes menu highlighting effect
1. Problem background and core principles
Menu navigation is a common element when building interactive web interfaces. We usually want to highlight when a user clicks on a menu item to clearly indicate the current selection or activity status. However, if handled improperly, all clicked menu items may remain highlighted, which obviously does not meet the expectations of "single-choice".
In order to achieve the effect of highlighting only one menu item at a time, the core principle is: when any menu item is clicked, first clear the current activation state of all menu items (that is, remove their activation style), and then accurately apply the activation style to the currently clicked menu item. This "clear everything first, then activate the current" mode is the key to achieving the exclusive selection state.
2. Page structure (HTML)
First, we need a clear HTML structure to represent our menu. Below is a typical side navigation menu structure with multiple div.menu_headers as clickable menu titles.
<nav id="nav_menu_query_off"> <menu id="main_menu"> <li class="main_list_item"> <div class="menu_header">Menu One</div> <div class="menu_body"> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> </div> </li> <li class="main_list_item"> <div class="menu_header">Menu 2</div> <div class="menu_body"> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> </div> </li> <li class="main_list_item"> <div class="menu_header">Menu Three</div> <div class="menu_body"> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> </div> </li> <li class="main_list_item"> <div class="menu_header">Menu Four</div> <div class="menu_body"> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> <menu class="sub_menu"></menu> </div> </li> </menu> </nav>
3. Style Definition (CSS)
To enable obvious visual feedback on menu items when activated, we define a CSS class, such as .active_red. When this class is added to a menu item, its text color will change to red. At the same time, we also include some basic menu layouts and styles.
* { margin: 0; padding: 0; box-sizing: border-box; text-decoration: none; list-style: none; } body { font-family: 'Ebrima'; background-color: #444444; } nav#nav_menu_query_off { position: fixed; top: 0; left: 0; width: 200px; height: 100vh; background-color: #222222; overflow: auto; z-index: 2; padding: 20px 0 20px 20px; } nav#nav_menu_query_off menu#main_menu li.main_list_item div.menu_header { text-transform: uppercase; padding-bottom: 10px; cursor: pointer; /* Indication element can be clicked*/ } nav#nav_menu_query_off menu li { color: #f0f0f0; } nav#nav_menu_query_off menu#main_menu li.main_list_item:not(:first-child) { padding-top: 20px; } .active_red { color: red; /* The text color changes to red when activated*/ } nav::-webkit-scrollbar { display: none; /* Hide scrollbar*/ }
4. Interaction logic (JavaScript)
This is the core part of achieving the single-choice highlighting effect. We will use JavaScript to listen for click events for each menu item and perform the "Clear all, activate current" logic when the event is triggered.
// 1. Get all elements with the 'menu_header' class const menuHeaders = document.querySelectorAll('.menu_header'); // 2. Define a helper function to remove 'active_red' class from a set of elements function removeActiveClass(elements) { elements.forEach(el => el.classList.remove('active_red')); } // 3. Add click event listener for each menuHeaders.forEach(head => { head.addEventListener('click', () => { // Each time you click, first remove the 'active_red' class of all menu items // This step is to ensure that only the current click item is highlighted with the key removeActiveClass(menuHeaders); // Then add the 'active_red' class to the currently clicked element head.classList.add('active_red'); }); });
Code parsing:
- document.querySelectorAll('.menu_header'): This line of code is used to select all elements on the page with the menu_header class. It returns a NodeList, which is an array-like collection containing all matching elements.
- removeActiveClass(elements) function: This is an encapsulated helper function that traverses the incoming element collection and removes the active_red class from the classList of each element. This implements the logic of "clear everything".
- menuHeaders.forEach(head => { ... }): We iterate through each menu header element in the menuHeaders collection and add a click event listener to each.
- Inside the event listener:
- removeActiveClass(menuHeaders): This is the most critical step. When any menu item is clicked, we first call this function to ensure that all menu items (including those that were previously activated) are restored to the inactive state.
- head.classList.add('active_red'): Next, we add the active_red class to the currently clicked head element to highlight it.
In this way, no matter which menu item the user clicks, the system will first "reset" the status of all menu items, and then "set" the status of the current click item, thus ensuring the effect of single-choice highlighting.
5. Things to note
- Initial activation state: If you want a menu item to be active by default when the page is loaded, you can add the active_red class directly to its HTML tag, or manually activate the first or specified menu item through code after JavaScript is loaded.
- Performance Considerations: For extreme cases where there are a large number of menu items, there may be a slight performance overhead when traversing all elements with each click to remove the class. In this scenario, you can consider using Event Delegation for optimization, that is, only an event listener is added to the parent element of the menu, and through the event bubble mechanism, it is used to determine which child element is clicked and process it accordingly. But for menus of average size, the current approach is efficient enough and easy to understand.
- Semantics and Accessibility: To improve user experience and accessibility, especially for users using screen readers, consider adding ARIA attributes, such as aria-current="page" or aria-selected="true" to the activated menu item to more explicitly indicate the status of the current item.
- CSS transition effect: If you want the highlighting effect to be smoother when switching, you can add a transition attribute to .menu_header in CSS, such as transition: color 0.3s ease;.
6. Summary
This tutorial explains in detail how to use JavaScript and CSS to achieve the single-choice highlighting effect of menu items. The core lies in the use of the logical mode of "clear everything first, then activate the current". This mode is not only suitable for menu highlighting, but also widely used in various UI components that require exclusive selection status, such as tabs, accordions, etc. Mastering this basic model will greatly help you build a more interactive, user-friendly and logical web interface.
The above is the detailed content of JavaScript realizes menu highlighting effect. 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)

To create an HTML unordered list, you need to use a tag to define a list container. Each list item is wrapped with a tag, and the browser will automatically add bullets; 1. Create a list with a tag; 2. Each list item is defined with a tag; 3. The browser automatically generates default dot symbols; 4. Sublists can be implemented through nesting; 5. Use the list-style-type attribute of CSS to modify the symbol style, such as disc, circle, square, or none; use these tags correctly to generate a standard unordered list.

Using tags is the easiest and recommended method. The syntax is suitable for modern browsers to embed PDF directly; 2. Using tags can provide better control and backup content support, syntax is, and provides download links in tags as backup solutions when they are not supported; 3. It can be embedded through Google DocsViewer, but it is not recommended to use widely due to privacy and performance issues; 4. In order to improve the user experience, appropriate heights should be set, responsive sizes (such as height: 80vh) and PDF download links should be provided so that users can download and view them themselves.

ThecontenteditableattributemakesanyHTMLelementeditablebyaddingcontenteditable="true",allowinguserstodirectlymodifycontentinthebrowser.2.Itiscommonlyusedinrichtexteditors,note-takingapps,andin-placeeditinginterfaces,supportingelementslikediv

To add an icon to the website title bar, you need to link a favicon file in part of the HTML. The specific steps are as follows: 1. Prepare a 16x16 or 32x32 pixel icon file. It is recommended to use favicon.ico to name it and place it in the website root directory, or use modern formats such as PNG and SVG; 2. Add link tags to HTML, such as PNG or SVG formats, adjust the type attribute accordingly; 3. Optionally add high-resolution icons for mobile devices, such as AppleTouchIcon, and specify different sizes through the sizes attribute; 4. Follow best practices, place the icon in the root directory to ensure automatic detection, clear the browser cache after update, and check the correctness of the file path.

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Usetheelementwithinatagtocreateasemanticsearchfield.2.Includeaforaccessibility,settheform'sactionandmethod="get"attributestosenddatatoasearchendpointwithashareableURL.3.Addname="q"todefinethequeryparameter,useplaceholdertoguideuse

First, check whether the src attribute path is correct, and ensure that the relative or absolute path matches the HTML file location; 2. Verify whether the file name and extension are spelled correctly and case-sensitive; 3. Confirm that the image file actually exists in the specified directory; 4. Use appropriate alt attributes and ensure that the image format is .jpg, .png, .gif or .webp widely supported by the browser; 5. Troubleshoot browser cache issues, try to force refresh or directly access the image URL; 6. Check server permission settings to ensure that the file can be read and not blocked; 7. Verify that the img tag syntax is correct, including the correct quotes and attribute order, and finally troubleshoot 404 errors or syntax problems through the browser developer tool to ensure that the image is displayed normally.

The novalidate attribute is used to disable the browser's default form verification; 1. After adding novalidate, the browser will not perform the default verification even if the input field contains constraints such as required, pattern, min, max, etc.; 2. The form will ignore whether the input is valid and submitted directly, which is suitable for custom verification using JavaScript, multi-step forms or temporary bypass verification in the development testing stage; 3. It is a Boolean property that does not require assignment, and acts on the entire form; 4. Remove novalidate to restore the normal verification behavior of the browser; therefore, novalidate enables developers to independently control the timing and method of form verification.
