Web Front-end
HTML Tutorial
JavaScript implements automatic closing of responsive navigation menu
JavaScript implements automatic closing of responsive navigation menu

This article will guide you on how to implement the function of automatically closing the menu after clicking an internal link in a responsive navigation menu. By adding a unified event listener to the navigation item, when the user selects any navigation link, the system will remove the display style of the menu, thus improving the user experience and avoiding the problem of the menu blocking content or needing to be closed manually.
Introduction: Optimizing the user experience of responsive navigation menus
In modern web design, responsive navigation menus (often presented as a "hamburger" icon) are an indispensable component on mobile devices. It allows users to access complete navigation options within limited screen space. However, a common user experience problem is that after a user clicks a link in the menu and navigates to a specified area of the page, the menu remains open, blocking the page content and requiring the user to close it manually. This article will introduce in detail how to elegantly solve this problem through JavaScript and realize the automatic closing of the menu after clicking the navigation link.
Analysis of existing menu structure and functions
To better understand the problem and solution, let's first review the implementation of a typical responsive navigation menu.
HTML structure: A menu usually consists of a trigger button (such as a hamburger icon) and a list containing navigation links.
<header>
<div class="hamburger" id="hamburger"></div>
<ul class="list" id="list">
<li><a href="#home">HOME</a></li>
<li><a href="#services">SERVICES</a></li>
<li><a href="#about">ABOUT</a></li>
<li><a href="#menu">MENU</a></li>
</ul>
</header>
<div class="contents">
<h1 id="home">HOME</h1>
<h1 id="services">SERVICES</h1>
<h1 id="about">ABOUT</h1>
<h1 id="menu">MENU</h1>
</div>
CSS style: Control the initial hidden state of the menu through CSS and define a .show class to make it visible.
.list {
list-style-type: none;
display: none; /* hidden by default */
}
.list.show {
position: fixed;
display: block;
inset: 0 0 0 0;
z-index: 99;
text-align: center;
background-color: hsl(0 0% 0% / 0.6);
padding: min(43vh, 20rem) 2rem;
}
/* Other related styles, such as .hamburger */
.hamburger {
width: 50px;
height: 50px;
background-color: red;
cursor: pointer;
position: absolute;
z-index: 999;
}
JavaScript logic: A simple JavaScript snippet is used to listen to the click event of the hamburger button to switch the show class of the navigation list.
const button = document.getElementById("hamburger");
const list = document.getElementById("list");
button.addEventListener("click", () => {
list.classList.toggle('show'); // Toggle menu display/hide});
Core problem: The menu does not close automatically after clicking the navigation link
In the above setup, when the user clicks on the hamburger button, the navigation menu expands (show class added). However, once the user clicks on any navigation link in the menu (such as HOME or ABOUT), the page scrolls to the corresponding anchor, but the menu itself remains open. Not only does this take up screen space, it may also prevent users from seeing the intended content, affecting the overall user experience.
Solution: Add a close event listener for navigation links
In order to solve this problem, we need to actively trigger the closing operation of the menu when the user clicks the navigation link.
Step 1: Optimize the HTML structure and add unified identification to navigation links
First, add a shared class name, such as nav-item, to all navigation link elements. This allows us to easily select all these links via JavaScript.
Step 2: Write JavaScript logic to monitor link click events
Next, modify the JavaScript code. Outside of the hamburger button's event listener, we need:
- Get all navigation links with nav-item class.
- Iterate through the links and add a click event listener for each link.
- In each link's click event handler, remove the show class on the navigation list list.
const button = document.getElementById("hamburger");
const list = document.getElementById("list"); // Make sure the list element has obtained button.addEventListener("click", () => {
list.classList.toggle('show');
});
// Get all navigation links const navItems = document.querySelectorAll('.nav-item');
// Add click event listener for each navigation link navItems.forEach((navItem) => {
navItem.addEventListener('click', () => {
list.classList.remove("show"); // Remove the 'show' class and close the menu});
});
Through the above modifications, when the user clicks on any navigation link, the show class on the list element will be removed immediately, thereby realizing the automatic closing of the menu. At the same time, the browser will handle the default behavior of the tag, making the page scroll smoothly to the corresponding anchor point.
Complete sample code
Here is the HTML and JavaScript snippet with all the modifications integrated, leaving the CSS unchanged:
<header>
<div class="hamburger" id="hamburger"></div>
<ul class="list" id="list">
<li><a href="#home" class="nav-item">HOME</a></li>
<li><a href="#services" class="nav-item">SERVICES</a></li>
<li><a href="#about" class="nav-item">ABOUT</a></li>
<li><a href="#menu" class="nav-item">MENU</a></li>
</ul>
</header>
<div class="contents">
<h1 id="home">HOME</h1>
<h1 id="services">SERVICES</h1>
<h1 id="about">ABOUT</h1>
<h1 id="menu">MENU</h1>
</div>
<script>
const button = document.getElementById("hamburger");
const list = document.getElementById("list");
// Hamburger button click event: switch menu display/hide button.addEventListener("click", () => {
list.classList.toggle('show');
});
// Get all navigation links const navItems = document.querySelectorAll('.nav-item');
//Add click event for each navigation link: close menu</script>The above is the detailed content of JavaScript implements automatic closing of responsive navigation menu. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
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
20522
7
13634
4
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)
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
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 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
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.
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 add prompt copy for disabled button click
Mar 30, 2026 pm 04:30 PM
This article introduces a complete solution for disabling the "Next" button when the form does not meet the conditions, and using native HTML5 form validation or JavaScript dynamic control to display a friendly prompt message when the disabled button is clicked.
How to switch images by clicking a button (elegant implementation based on jQuery)
Apr 04, 2026 pm 08:06 PM
This article introduces how to use jQuery to dynamically switch background images after button clicks, and corrects problems such as CSS selector misuse, inline event coupling, and logical redundancy in the original code, providing a concise and maintainable interaction solution.





