Bootstrap: Navbar links do not receive active class in the scroll on time

I am utilizing Bootstrap 4.

After implementing a smooth scroll feature, I had to adjust it by 80px due to my fixed navbar at the top.

$('#navbar').find('a').click(function (event) {
        event.preventDefault();
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - 80
        }, 750);
    });

However, I am struggling with adjusting Bootstrap's active class on the links. The class is only applied when the anchored section reaches the top of the browser screen, but my navbar overlaps.

Do you have any suggestions?

Thank you for your assistance!

Answer №1

Try implementing this solution:

$(document).ready(function() {
    $('.navbar-nav a').click(function (event) {
        event.preventDefault();

        var target = $(this).attr("href");
        var targetOffset = $(target).offset().top - 80;
      
        $('html, body').stop().animate({
            scrollTop: targetOffset
        }, 750);
    });
});

$(window).scroll(function() {
    // Get windows scroll top offset and add your 80px. You can add the section padding or margin if you like.
    var windowScroll = $(window).scrollTop() + 80;

    // Assign active class to nav links while scrolling
    // (index) will return how many sections you have
    // Replace (section) with your sections class
    $('section').each(function(index) {         
        // Check offset
        if ( $(this).offset().top <= windowScroll ) {
            $('.navbar-nav a.active').removeClass('active');
            $('.navbar-nav a').eq(index).addClass('active');
        }
    });

}).scroll();
.wrap {
  margin-top: 100px
}
section {
  min-height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

<nav id="navbar" class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="#section1">section1</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#section2">section2</a>
            </li>

            <li class="nav-item dropdown">
                <a class="nav-link" href="#section3">section3</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#section4">section4</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#section5">section5</a>
            </li>
        </ul>
    </div>
</nav>

<div class="container wrap">
    <section id="section1" class="jumbotron">
        <h4>Section 1</h4>
            <p>Providing a sample text for Section 1.</p>  
    </section>
    
    <section id="section2" class="jumbotron">
        <h4>Section 2</h4>
            <p>A placeholder text for Section 2.</p>  
    </section>
    <section id="section3" class="jumbotron">
        <h4>Section 3</h4>
            <p>Insert content for Section 3 here.</p>  
    </section>
    <section id="section4" class="jumbotron">
        <h4>Section 4</h4>
            <p>Customize information for Section 4 as needed.</p>  
    </section>
    <section id="section5" class="jumbotron">
        <h4>Section 5</h4>
            <p>Populate this section with relevant data.</p>  
    </section>
</div>

Answer №2

After some experimenting, I decided to modify my approach by increasing the padding on the sections and removing the 80px adjustment in the JavaScript code. As a result, the navbar now overlaps with the 80px padding instead. While this isn't exactly the outcome I was aiming for, it does the job for now.

If anyone has a solution that aligns more closely with my original vision, I would love to hear it!

Appreciate any input

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Design a dynamic dropdown feature that is triggered when the chip element is clicked within the TextField component

Currently, I am facing difficulties in implementing a customized dropdown feature that is not available as a built-in option in Material UI. All the components used in this project are from Material UI. Specifically, I have a TextField with a Chip for the ...

Altering the playback of a flash object using HTML or JavaScript

Can the playback speed of a flash object be adjusted without recompiling the object, like through HTML attributes or JavaScript? Appreciate any help in advance ...

Issue encountered during upgrade from version 10 to version 13 in a Next.js migration: Module not found

I've been working on upgrading our old site from version 10 to version 13, and we have a custom backend built with express. However, I keep encountering a "Module not found" error when running the project concurrently, specifically when running the cl ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Ways to effectively conceal an HTML div element with CSS or JavaScript

Is there a way to hide the div element that is nested inside a bootstraps radio or checkbox container using jquery? I'm unable to upload an image, but here is a preview: http://prntscr.com/6wrk2m <style> .my-radio{ border: 1px solid #F0F; } &l ...

Ensuring that a canvas remains centered and completely visible within its parent element while zooming in React

Currently, I am developing a straightforward PowerPoint creator using React. In this project, I have integrated a zoom feature for a canvas element. The principle is that the canvas should resize based on a scale factor. However, there seems to be an issue ...

I'm curious about how I can selectively utilize vuex-persistedstate with Nuxt for certain stores only

Check out this library: https://github.com/robinvdvleuten/vuex-persistedstate. I have customized the provided plugin file for Nuxt. import createPersistedState from 'vuex-persistedstate' export default ({ store }) => { createPersistedState ...

What is the most efficient way to retrieve a substantial volume of data from Mongodb quickly, especially when the query results require processing before transmitting to the client?

My project involves a large Mongodb database paired with a React front-end and Node back-end, housing around 100000 documents. Indexing has been completed and Redis is already in use. The search feature implemented allows users to find relevant documents b ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Having trouble displaying the desired formatting when mapping through nested JSON in Node ES6

Currently working on a project to build a photo gallery using nested JSON data. My goal is to iterate through the data and create a well-structured JavaScript object or a smaller JSON file that includes only the text and image URL nodes. However, my curren ...

Reload iframe content using a .php file within a different iframe

I am currently working on a page that consists of 7 different iframes: <iframe id="leftframe" src="structure/leftbar.php"></iframe> <iframe id="headerframe" src="structure/header.php"></iframe> <iframe id="menuframe" src="struct ...

What is the origin of this mysterious error?

I'm working on a function to format various types of variables and utilize a toString() method. It's handling complex objects, arrays, and circular references flawlessly. However, when testing it on a jQuery object using format($("body")) with l ...

Is there a substitute for useState in a Next.js server component?

With my static site at , the only interactive feature being the dark mode toggle, I understand that using useState is not feasible in a server component. export default function RootLayout({ children }: { children: React.ReactNode }) { const [darkMode, ...

Execute the calculation on the user's AWS account

In my Node.js and Vue.js project, the goal is for a user to input their AWS credentials, provide a link to an online data source containing a large amount of data, and run an algorithm on this data using their provided AWS account. I am facing two challen ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

What is the best way to set an initial value retrieved from the useEffect hook into the textField input field?

I am working on an edit page where the initial values of first name, last name, and address are fetched from Firebase Firestore using useEffect. useEffect(() => { const unsubscribe = firestore .collection("users") .doc(uid) ...

What is the best way to access the front camera on both Android and iOS devices in order to capture a photo using Vue.J

I am currently developing a PWA Vue.Js application and I am trying to implement a feature that allows users to take a picture with the front camera on their mobile devices. Although I have managed to write code that works on my desktop browser, I have bee ...

Leveraging em units in jQuery Script

I'm currently in the process of building a website and I'm facing an issue with converting measurements to em's. The script that I have reused from a previous project only seems to work with pixels, despite my efforts to make it compatible w ...

I'm puzzled as to why a div tag suddenly becomes invisible when I attempt to link it with a v-for directive in my code

I am facing an issue with the div tag assigned to the log class. My objective is to populate the text using data retrieved from the API response. However, when I attempt to include the v-for directive, the entire div mysteriously disappears from the brow ...

Merge JSON objects into an array

Is there a way to merge JSON objects when the initial object is: { "total": "2" } And the second one is: [ "player1": { "score": "100", "ping": "50" }, "player2": { "score": "100", "ping": "50" ...