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
Problem analysis: Event listener binding error
Solution: Correctly bind window scroll events
HTML structure example
Notes and Summary
Home Web Front-end HTML Tutorial Solve the problem of JavaScript sidebar smooth scrolling and navigation highlighting failure

Solve the problem of JavaScript sidebar smooth scrolling and navigation highlighting failure

Nov 07, 2025 pm 11:21 PM

Solve the problem of JavaScript sidebar smooth scrolling and navigation highlighting failure

This article aims to solve the problem that the click anchor point in the JavaScript sidebar cannot scroll smoothly to the specified area, and the navigation link highlighting fails when scrolling. The core is to correctly bind the global scroll event listener to the `window` object instead of an undefined variable, and to ensure that the jQuery library has been correctly introduced to achieve the expected smooth scrolling and navigation state update effects.

When building a web page with a side navigation bar, we often need to achieve a smooth scrolling of the page to the corresponding content area when a navigation link is clicked, and update the activation status of the navigation link in real time. However, in actual development, developers may encounter problems with scrolling function failure, especially deviations in the binding of event listeners. This tutorial will delve into the root causes of such problems and provide a set of reliable solutions.

Problem analysis: Event listener binding error

In the original code, the logic of smooth scrolling, navigation highlighting, and sticky sidebar positioning all rely on scroll events. However, the way e.addEventListener('scroll', ...) is written is wrong. e is usually passed as an event object inside an event handler, but using e directly as the target object of addEventListener in the global scope is undefined. Global scroll events should be bound to the window object.

Solution: Correctly bind window scroll events

To resolve the above issue, simply replace all calls to e.addEventListener('scroll', ...) with window.addEventListener('scroll', ...). The window object represents the browser window and is the correct target to listen for global scroll events.

Here is the corrected JavaScript code example:

 // Make sure the jQuery library has been introduced // <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

$(document).ready(function () {
    // 1. Click the navigation link to smoothly scroll to the specified area $('a[href*=\\#]').on('click', function (e) {
        // e.preventDefault(); // You can cancel the default hash jump behavior to achieve pure smooth scrolling // If you need the page URL hash to be updated with scrolling, do not cancel the default behavior, or update it manually var target = $(this).attr("href"); // Get the ID of the target element
        if ($(target).length) { // Check if the target element exists $('html, body').animate({
                scrollTop: $(target).offset().top // Calculate the top offset of the target element}, 600); // The scroll animation duration is 600 milliseconds}
    });

    // 2. Update the activation status of the navigation link when scrolling window.addEventListener('scroll', () =&gt; {
        var scrollDistance = $(window).scrollTop(); // Get the current scroll distance // Traverse all content sections and activate the corresponding navigation link according to the scroll position $('.page-section').each(function (i) {
            // When the top position of the content section is less than or equal to the current scroll distance, activate its corresponding navigation link if ($(this).position().top  {
        var currentScroll = $(window).scrollTop(); // Get the current scroll distance if (currentScroll &gt;= fixmeTop) {
            // When the scroll distance exceeds the initial position of the navigation bar, position it as fixed
            $('.navigation').css({
                position: 'fixed',
                top: '80px', // Adjust to a suitable value, such as 80px from the top
                float: 'left' // keep floating });
        } else {
            // Otherwise, revert to absolute positioning $('.navigation').css({
                position: 'absolute',
                top: '50px', //Restore to initial position or appropriate value float: 'left'
            });
        }
    });
});

HTML structure example

In order for the above JavaScript code to work properly, a matching HTML structure is required. Here is a complete HTML example including sidebar navigation and content sections:

 


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sidebar scroll navigation tutorial</title>
    <!--Introducing the jQuery library-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <style>
        /* Sample CSS style, used to demonstrate the effect*/
        body { margin: 0; font-family: sans-serif; }
        .side-overlay { 
            position: fixed; 
            top: 0; 
            left: 0; 
            width: 100%; 
            height: 100%; 
            background-color: rgba(0,0,0,0.5); 
            z-index: 1000; 
            display: block; /* In the example, it is set to block. In actual applications, the display and hiding may be controlled through JS*/
        }
        .faq_sidebar { 
            width: 300px; /* Sidebar width*/
            height: 100%; 
            background-color: #fff; 
            position: absolute; 
            left: 0; 
            top: 0; 
            overflow-y: auto; /* The inside of the sidebar is scrollable*/
            padding-top: 20px;
        }
        .faq-section1 { padding: 20px; border-bottom: 1px solid #eee; }
        .faq_close { text-align: right; }
        .navigation { 
            padding: 20px; 
            width: 260px; /* Navigation bar width*/
            background-color: #f8f8f8;
            border-right: 1px solid #eee;
            box-sizing: border-box;
            z-index: 10; /* Make sure sticky navigation is above the content*/
            /* Initial positioning will be overwritten by JS*/
            position: absolute; 
            top: 50px; 
            float: left;
        }
        .navigation__link { 
            display: block; 
            padding: 10px 15px; 
            text-decoration: none; 
            color: #333; 
            border-left: 3px solid transparent; 
            margin-bottom: 5px;
        }
        .navigation__link:hover { background-color: #e0e0e0; }
        .navigation__link.active { 
            background-color: #e6f7ff; 
            color: #1890ff; 
            border-left-color: #1890ff; 
            font-weight: bold;
        }
        .tab-content { 
            margin-left: 300px; /* Leave space for the sidebar*/
            padding: 20px;
        }
        .page-section { 
            min-height: 600px; /* Ensure that each section has sufficient scroll height*/
            padding: 40px 0; 
            border-bottom: 1px solid #eee; 
        }
        .page-section:last-child { border-bottom: none; }
        h1 { margin-top: 0; }
    </style>


    <div class="side-overlay" id="side-overlay">
        <div class="faq_sidebar" id="faqs">
            <div class="container-fluid faq-section1">
                <div class="row">
                    <div class="col-md-11">
                        <h5 class="subscription-subhead">FAQ's</h5>
                        <h2 class="subscription-title js-scroll fade-in-bottom">
                            You have questions, we have answers
                        </h2>
                    </div>
                    <div class="col-md-1 faq_close">
                        <a href="javascript:void(0)" id="closefaqx" class="closebtn_faq" onclick="closeFaq()">
                            <img src="./images/cross%20X.png" alt="" class="closebar">
                        </a>
                    </div>
                </div>
            </div>

            <div class="faq_section2">
                <nav class="navigation" id="mainNav">
                    <a class="navigation__link" href="#1">What is Lorem Ipsum?</a>
                    <a class="navigation__link" href="#2">Why do we use it?</a>
                    <a class="navigation__link" href="#3">Where does it come from?</a>
                    <a class="navigation__link" href="#4">Where can I get some?</a>
                    <a class="navigation__link" href="#5">What is Lorem Ipsum?</a>
                </nav>

                <div class="tab-content">
                    <div class="nestednav">
                        <div class="page-section hero" id="1">
                            <h1>Section 1: What is Lorem Ipsum?</h1>
                            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                        </p>
</div>
                        <div class="page-section" id="2">
                            <h1>Section 2: Why do we use it?</h1>
                            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                        </p>
</div>
                        <div class="page-section" id="3">
                            <h1>Section 3: Where does it come from?</h1>
                            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                        </p>
</div>
                        <div class="page-section" id="4">
                            <h1>Section 4: Where can I get some?</h1>
                            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                        </p>
</div>
                        <div class="page-section" id="5">
                            <h1>Section 5: What is Lorem Ipsum?</h1>
                            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                        </p>
</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Notes and Summary

  1. jQuery dependency : The sample code makes heavy use of the jQuery library, so be sure to include jQuery within the tag of your HTML file. It is recommended to use a CDN link, such as https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js.
  2. Event target : It is important to understand that the first parameter to addEventListener is the target object of the event. For global events, such as scrolling (scroll), window resizing (resize), etc., they should usually be bound to the window object.
  3. e.preventDefault() : In the click event handler, e.preventDefault() is used to prevent the browser from executing the default jump behavior of the anchor link. If you want full control over smooth scrolling animations via JavaScript and avoid changes in URL hashes, you should uncomment this line. If you want the URL hash to update as you scroll, you can not use e.preventDefault(), or manually update window.location.hash after the animation completes.
  4. Offset adjustment : When calculating the activation state, the 100 in if ($(this).position().top
  5. CSS styles : For better visual effects, make sure to define appropriate CSS styles for the .navigation__link.active class so that it is clearly distinguishable when activated. At the same time, the top value of sticky navigation also needs to be fine-tuned according to the page layout.
  6. Performance considerations : Scroll events may be triggered frequently. If the event handling function contains complex DOM operations or calculations, page performance may be affected. In actual projects, you can consider using throttling or debounce technology to optimize the processing of scroll events.

By correctly understanding and using window.addEventListener, we can effectively solve the problem of smooth scrolling and navigation highlighting failure in JavaScript sidebars, thereby providing a smoother and more intuitive user experience.

The above is the detailed content of Solve the problem of JavaScript sidebar smooth scrolling and navigation highlighting failure. 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