search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Analysis of existing problems
Solution: Optimize event monitoring and status management
1. JavaScript code optimization
2. CSS style coordination
Things to note and best practices
Summarize
Home Web Front-end HTML Tutorial Optimize mobile navigation: realize the automatic closing function of clicking menu items

Optimize mobile navigation: realize the automatic closing function of clicking menu items

Nov 27, 2025 pm 09:57 PM

Optimize mobile navigation: realize the automatic closing function of clicking menu items

This tutorial aims to solve the user experience problem of the mobile navigation menu not automatically closing after clicking any menu item. We will optimize the JavaScript event listening mechanism, bind the click event to the entire navigation menu container, and dynamically switch the display state of the menu with CSS styles, so that the navigation menu can be automatically closed after clicking on a menu item, switch button or menu area, improving the smoothness and intuitiveness of user interaction.

In modern responsive web design, mobile navigation menu usability is crucial. A common user experience pain point is that when the user clicks a link in the expanded mobile navigation menu to jump to a certain area of ​​the page, the menu remains expanded and requires the user to manually click the toggle button to collapse it. This not only increases the user's operation steps, but may also block the page content and affect the browsing experience. This tutorial will provide a simple and efficient solution to intelligently close the navigation menu by adjusting JavaScript event listening and CSS styles.

Analysis of existing problems

Typically, mobile navigation menu expansion and collapse is controlled through a toggle button (such as a hamburger icon). The JavaScript code will listen to the click event of this button, and then add or remove a specific CSS class (such as active) for the navigation menu container to control the display and hiding of the menu.

Here is an example of a typical HTML structure and initial JavaScript code:

HTML structure:

 <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" rel="stylesheet">
<nav id="navbar">
    <ul class="menu">
        <li class="logo"><a href="#"><img  src="img/LOGO%20JS%20BLANCO%20PNG.png" alt="Optimize mobile navigation: realize the automatic closing function of clicking menu items" ></a></li>
        <li class="item"><a href="#home">Home</a></li>
        <li class="item"><a href="#about">About</a></li>
        <li class="item"><a href="#portfolio">Portfolio</a></li>
        <li class="item"><a href="#knowledge">Knowledge</a></li>
        <li class="item"><a href="#experience">Experience</a></li>
        <li class="item"><a href="#contact">Contact</a></li>
        <li class="toggle"><a href="#nowhere"><i class="fas fa-bars"></i></a></li>
    </ul>
</nav>

Original JavaScript code (only listens to the toggle button):

 const toggle = document.querySelector(".toggle");
const menu = document.querySelector(".menu");

/* Toggle mobile menu */
function toggleMenu() {
  if (menu.classList.contains("active")) {
    menu.classList.remove("active");
    toggle.querySelector("a").innerHTML = "<i class="'fas" fa-bars></i>";
  } else {
    menu.classList.add("active");
    toggle.querySelector("a").innerHTML = "<i class="'fas" fa-times></i>";
  }
}

/* Event Listeners */
toggle.addEventListener("click", toggleMenu, false);
// The original code may have other event listeners for item, but usually does not include the logic of closing the menu // for (let item of items) {
// item.addEventListener("keypress", toggleItem, false);
// }

In the above code, the toggleMenu function is responsible for switching the active class of the menu element and updating the icon of the toggle button. However, the line toggle.addEventListener("click", toggleMenu, false); clearly states that the menu will only switch states when the .toggle element (that is, the hamburger icon) is clicked. When the user clicks on the link in .item, the toggleMenu function will not be triggered, causing the menu to fail to close automatically.

Solution: Optimize event monitoring and status management

To solve this problem, the core idea is to associate the closing logic of the menu with the click behavior of the menu item. The most direct and effective method is to extend the event listener from a single toggle button to the entire navigation menu container. The menu's toggle function is triggered when any area within the menu (including the menu item or the toggle button itself) is clicked.

1. JavaScript code optimization

We will modify the JavaScript code to achieve the following goals:

  • Move the click event listener from the .toggle element to the entire .menu element.
  • Simplify the toggleMenu function and use the classList.toggle method to make the code more concise.
  • Dynamically toggle the toggle button's icon to reflect the menu's current state.

Optimized JavaScript code:

 const toggle = document.querySelector(".toggle");
const menu = document.querySelector(".menu");

/* Toggle mobile menu - after optimization*/
function toggleMenu() {
  // Use classList.toggle to simplify the add/remove logic of active classes menu.classList.toggle("active");

  // Get the icon element in the toggle button const icon = toggle.querySelector("a i.fas");

  // Use classList.toggle to simplify icon class switching icon.classList.toggle('fa-bars'); // Switch to the hamburger icon icon.classList.toggle('fa-times'); // Switch to the close icon}

/* Event Listeners - Bind listeners to the entire menu */
menu.addEventListener("click", toggleMenu, false);

Code explanation:

  1. menu.classList.toggle("active");: This is a concise replacement for if/else statements. If the menu element contains the active class, it will be removed; if it does not, it will be added.
  2. const icon = toggle.querySelector("a i.fas");: The Font Awesome icon element inside the toggle button is precisely selected.
  3. icon.classList.toggle('fa-bars'); and icon.classList.toggle('fa-times');: also use the toggle method to synchronously switch icons according to the status of the active class. When the menu is expanded, fa-bars are removed and fa-times are added; when the menu is collapsed, the opposite is true.
  4. menu.addEventListener("click", toggleMenu, false);: This is the key change. Now, any click event that occurs inside the .menu element (including clicking on the link in the .item, the .toggle button, or even the .logo) will trigger the toggleMenu function, thereby expanding or collapsing the menu.

2. CSS style coordination

In order for the above JavaScript code to work, we also need to ensure that the CSS style correctly shows or hides the menu items based on whether the menu element has the active class. In mobile view, menu items should be hidden by default and only shown when the menu has active class.

Key CSS styles:

 /* By default, menu items are hidden*/
#navbar .item {
  display: none;
}

/* When the menu is active, display the menu items */
#navbar .menu.active .item {
  display: list-item; /* or block/flex, depending on specific layout requirements*/
}

/* Ensure that the toggle button is always visible on mobile */
#navbar .toggle {
  display: block; /* or flex to ensure display on the mobile end*/
}

/* Adjust other styles as needed, such as displaying all menu items on desktop */
@media (min-width: 768px) { /* Example breakpoint*/
  #navbar .item {
    display: list-item; /* Display all menu items on desktop */
  }
  #navbar .toggle {
    display: none; /* Hide the toggle button on desktop */
  }
}

Style explanation:

  • #navbar .item { display: none; }: This line of CSS ensures that all menu items are hidden in the default state (that is, when the menu does not have an active class).
  • #navbar .menu.active .item { display: list-item; }: When the .menu element is added with the active class by JavaScript, these menu items will be displayed. list-item is suitable for li elements, and block or flex can also be selected according to the layout.
  • Media queries (@media) are used to differentiate between desktop and mobile views, ensuring that menu items are always visible on desktop, while toggle buttons are hidden.

Things to note and best practices

  1. Event bubbling and delegation : Binding an event listener to a parent element (.menu) is a form of event delegation. It uses the event bubbling mechanism, that is, events on child elements will bubble up to the parent element. The benefit of this approach is that even if menu items are added dynamically, they automatically inherit this behavior, eliminating the need to add a separate listener for each new menu item.
  2. User experience : This design assumes that the user intends to close the menu when clicking anywhere in the menu (including menu items, logos, or toggle buttons). This is reasonable in most mobile navigation scenarios. If there is a special requirement that clicking an element within the menu should not close the menu (for example, an inline search box or a toggle button for a submenu), more refined event judgment is required, such as checking event.target to exclude specific elements.
  3. Accessibility : Ensure that toggle buttons have the correct ARIA attributes (such as aria-expanded) to indicate the current state of the menu and allow keyboard users to navigate through the menu via the Tab key and activate the menu with the Enter key.
  4. Animation effects : In order to provide a smoother user experience, you can add CSS transition effects to the display/hide of the menu instead of simple display: none/block switching. For example, use max-height or transform properties for animation.
  5. Compatibility : The classList API is widely supported in modern browsers. If you need to support IE9 and below browsers, you may need to use the className attribute or Polyfill.

Summarize

By extending the JavaScript event listener from a single toggle button to the entire navigation menu container, and combining it with CSS styles to dynamically control the display of menu items, we successfully implemented the function of the mobile navigation menu automatically closing after clicking any menu item. This approach not only simplifies the code and improves maintainability, but more importantly, significantly improves the navigation experience for mobile users, making its operations more intuitive and efficient. In actual development, developers should further improve accessibility, animation effects and responsive layout based on specific project needs.

The above is the detailed content of Optimize mobile navigation: realize the automatic closing function of clicking menu items. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to correctly migrate jQuery's drag and drop events to native JavaScript How to correctly migrate jQuery's drag and drop events to native JavaScript Mar 06, 2026 pm 05:15 PM

This article explains in detail the key pitfalls when migrating jQuery drag-and-drop logic (such as dragover/dragleave) to Vanilla JS - especially the problem of misuse of e.originalEvent causing dataTransfer failure, and provides directly runnable fixes and best practices.

How to make the images in a div fill with no margins while retaining the inner margins of the text How to make the images in a div fill with no margins while retaining the inner margins of the text Mar 07, 2026 pm 10:54 PM

This article explains how to keep the overall padding of the container so that the internal images are displayed close to the edge of the container, while the text content still maintains normal padding - the core is to separate the style scope and achieve precise layout through positioning and box model control.

Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Mar 09, 2026 pm 08:15 PM

When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.

Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Mar 12, 2026 pm 08:51 PM

This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.

A complete guide to using the keyboard to control the smooth movement of HTML elements A complete guide to using the keyboard to control the smooth movement of HTML elements Mar 13, 2026 pm 10:18 PM

This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.

How to properly override default styles and implement custom CSS layouts in Divi theme builder How to properly override default styles and implement custom CSS layouts in Divi theme builder Mar 14, 2026 am 12:00 AM

This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.

How to dynamically pass HTML form data to analytics.track() method How to dynamically pass HTML form data to analytics.track() method Mar 13, 2026 pm 10:57 PM

This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.

How to optimize Lighthouse image scoring while maintaining high image quality How to optimize Lighthouse image scoring while maintaining high image quality Mar 11, 2026 pm 09:39 PM

This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.

Related articles