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
Introduction: Interactive challenges of mobile navigation menus
Infrastructure: Building a toggleable navigation menu
HTML structure
CSS styles
JavaScriptinteraction
Automatically close the menu when clicking on a navigation item
Core idea
Step 1: Modify the HTML and add a unified class name to the navigation link
Step 2: Write JavaScript to listen for navigation link click events
Complete code example
HTML (index.html)
CSS (style.css)
JavaScript (script.js)
Notes and optimization
Summarize
Home Web Front-end HTML Tutorial JavaScript implements automatic closing of mobile menu after clicking navigation link

JavaScript implements automatic closing of mobile menu after clicking navigation link

Nov 21, 2025 pm 08:27 PM

JavaScript implements automatic closing of mobile menu after clicking navigation link

This tutorial will guide how to use JavaScript to automatically close the full-screen overlay menu after clicking the navigation link in the hamburger menu in responsive web design. We will optimize the user experience by adding unified class names for navigation links and listening for click events, and removing CSS classes that control menu visibility.

Introduction: Interactive challenges of mobile navigation menus

In modern responsive web design, the Hamburger Menu is a common mobile navigation pattern. It usually exists as an icon that when clicked will expand a full-screen overlay or a navigation menu that slides out from the side. After opening the menu, users will expect that when they click any navigation link in the menu, they will not only be able to jump to the target page or page area, but the menu itself will also automatically close to provide a smooth and intuitive user experience. If the menu remains open after clicking the link, it will appear redundant and may prevent the user from viewing the content.

Infrastructure: Building a toggleable navigation menu

First, let's look at a typical hamburger menu and its initial interaction logic.

HTML structure

The following HTML code defines a header area that contains a "hamburger" button and a navigation list. The navigation list is hidden by default.

 <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 styles

CSS styles manage the display and hiding of menus by controlling the display attribute of the .list element and adding the .show class. When the .list element has the show class, it will be displayed in full screen coverage.

 /*Hide navigation list by default*/
.list {
    list-style-type: none;
    display: none;
    margin: 0;
    padding: 0;
}

/* When the .list element has the 'show' class, it is displayed as a full-screen overlay menu */
.list.show {
    position: fixed;
    display: block;
    inset: 0 0 0 0; /* Cover the entire viewport*/
    z-index: 99;
    text-align: center;
    background-color: hsl(0 0% 0% / 0.6); /* Semi-transparent background*/
    padding: min(43vh, 20rem) 2rem;
}

/* Hamburger button style (example) */
.hamburger {
    width: 50px;
    height: 50px;
    background-color: red;
    cursor: pointer;
    position: absolute;
    z-index: 999;
}

/* Other common styles*/
html {
    scroll-behavior: smooth; /* Enable smooth scrolling */
}

JavaScriptinteraction

The following JavaScript code implements the display and hide switching function of the navigation list when the hamburger button is clicked:

 const button = document.getElementById("hamburger"); // Get the hamburger button const list = document.getElementById("list"); // Get the navigation list // Add a click event listener for the hamburger button button.addEventListener("click", () =&gt; {
    list.classList.toggle('show'); // Toggle the 'show' class of the navigation list});

At this point, we have implemented a basic hamburger menu that can be opened and closed by clicking a button. However, when the menu is opened, clicking the navigation link will not automatically close the menu. This is the core problem we need to solve.

Automatically close the menu when clicking on a navigation item

To solve the problem of the menu not closing after clicking a navigation link, we need to add additional event handling logic for each navigation link.

Core idea

Our goal is: when the user clicks any link in the navigation menu, in addition to triggering the default page scrolling or jumping behavior, the navigation menu must also be explicitly closed (that is, its show class is removed).

To easily select all navigation links and add event listeners to them, we can add a unified class name to each tag, such as nav-item.

 

By adding the nav-item class, we now have a unified selector for all navigation links we need to listen for.

Next, we need to modify the JavaScript code to implement the function of automatically closing the menu when clicking the navigation link.

 // Get the hamburger button and navigation list const button = document.getElementById("hamburger");
const list = document.getElementById("list");

// Get all navigation links with 'nav-item' class const navItems = document.querySelectorAll('.nav-item');

//Add a click event listener for the hamburger button to switch the menu display/hide button.addEventListener("click", () =&gt; {
    list.classList.toggle('show');
});

// Traverse all navigation links and add a click event listener for each link navItems.forEach((navItem) =&gt; {
    navItem.addEventListener('click', () =&gt; {
        // When the navigation link is clicked, remove the 'show' class of the navigation list, thereby closing the menu list.classList.remove("show");
    });
});

With the above modification, when the user clicks on the hamburger button, the menu will open or close. When the menu is opened and the user clicks any nav-item link in it, the show class of the menu will be removed, thereby automatically closing the menu, and the browser will scroll to the corresponding page anchor (if the link is an internal anchor).

Complete code example

To provide a complete reference, here is sample code that combines HTML, critical CSS, and JavaScript:

HTML (index.html)

 


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive navigation menu</title>
    <link rel="stylesheet" href="style.css">


    <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 src="script.js"></script>

CSS (style.css)

 body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
html {
    scroll-behavior: smooth; /* Enable smooth scrolling */
}
ul {
    list-style-type: none;
}
.list {
    list-style-type: none;
    display: none; /* hidden by default */
}
.list.show {
    position: fixed;
    display: block; /* Display with 'show' class */
    inset: 0 0 0 0; /* Cover the entire viewport*/
    z-index: 99;
    text-align: center;
    background-color: hsl(0 0% 0% / 0.6); /* Semi-transparent background*/
    padding: min(43vh, 20rem) 2rem;
}
header {
    display: flex;
    justify-content: space-between;
}
.hamburger {
    width: 50px;
    height: 50px;
    background-color: red; /* Example color*/
    cursor: pointer;
    position: absolute;
    z-index: 999;
}
h1 {
    margin: 20rem 0; /* Sample content spacing*/
}
.contents {
    position: absolute;
    left: 50%;
    top: 120%; /* Example positioning*/
    transform: translate(-50%, -50%);
}

JavaScript (script.js)

 const button = document.getElementById("hamburger"); // Get the hamburger button const list = document.getElementById("list"); // Get the navigation list // Get all navigation links with the 'nav-item' class const navItems = document.querySelectorAll('.nav-item');

//Add a click event listener for the hamburger button to switch the menu display/hide button.addEventListener("click", () =&gt; {
    list.classList.toggle('show');
});

// Traverse all navigation links and add a click event listener for each link navItems.forEach((navItem) =&gt; {
    navItem.addEventListener('click', () =&gt; {
        // When the navigation link is clicked, remove the 'show' class of the navigation list, thereby closing the menu list.classList.remove("show");
    });
});

Notes and optimization

  1. Event Delegation: For complex menus with a large number of navigation items, adding separate event listeners for each link may affect performance. In this case, event delegation can be used. That is, only add an event listener on the parent element (such as ul.list), and then use event.target to determine which sub-link was clicked, and execute the corresponding closing menu logic.

     list.addEventListener('click', (event) =&gt; {
        if (event.target.classList.contains('nav-item')) {
            list.classList.remove('show');
        }
    });

    This method can reduce memory usage and is especially suitable for scenarios where navigation items are dynamically added or removed.

  2. User experience and smooth scrolling: html { scroll-behavior: smooth; } CSS properties can ensure that the page scrolls smoothly when the anchor link is clicked, instead of jumping abruptly, which can significantly improve the user experience.

  3. Accessibility: For better accessibility, especially for screen reader users, it is recommended to add ARIA attributes to the hamburger button, such as aria-controls (ID pointing to the navigation list) and aria-expanded (indicating whether the menu is currently expanded). When the menu opens/closes, update the value of aria-expanded accordingly.

  4. Animation effect: If you want a smoother transition effect when the menu is closed, you can add a transition in CSS to the display attribute or other attributes that control the menu position/transparency. However, the display attribute usually cannot be directly transitioned. You can consider using opacity and visibility combined with transition.

Summarize

This tutorial details how to use JavaScript to automatically close the menu after clicking a link in the mobile navigation menu. The core idea is to use CSS classes to control the visibility of the menu, listen to the click event of the navigation link through JavaScript, and remove the CSS class that controls the display state of the menu when the event is triggered. This approach is simple, efficient, and easy to maintain, and is a critical step in achieving a good user experience. By flexibly using DOM operations and event listening, we can create a responsive, interactive and friendly web navigation system.

The above is the detailed content of JavaScript implements automatic closing of mobile menu after clicking navigation link. 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