How to implement smooth scrolling in Bootstrap 4.1 with Scrollspy integration?

I am currently working on integrating the scrollspy function from bootstrap 4.1 into my navbar and I have successfully implemented it. However, I am facing challenges in adding smooth scrolling to it. Despite extensive research on the web, I have been unable to resolve this issue.

Below is the code snippet that I am using (borrowed from Bootstrap).

<nav id="navbar-example2" class="navbar navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="nav nav-pills">
    <li class="nav-item">
      <a class="nav-link" href="#fat">@fat</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#mdo">@mdo</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</a>
      <div class="dropdown-menu">
        <a class="dropdown-item" href="#one">one</a>
        <a class="dropdown-item" href="#two">two</a>
        <div role="separator" class="dropdown-divider"></div>
        <a class="dropdown-item" href="#three">three</a>
      </div>
    </li>
  </ul>
</nav>
<div data-spy="scroll" data-target="#navbar-example2" data-offset="0">
  <h4 id="fat">@fat</h4>
  <p>...</p>
  <h4 id="mdo">@mdo</h4>
  <p>...</p>
  <h4 id="one">one</h4>
  <p>...</p>
  <h4 id="two">two</h4>
  <p>...</p>
  <h4 id="three">three</h4>
  <p>...</p>
</div>

Here is the additional script I attempted to add for achieving smooth scrolling:


<script>
    $(document).ready(function() {
        $(".nav-item").click(function() {
            var target = $(this).attr("href");
            $('.active').removeClass('active');
            $("html, body").animate({
                scrollTop: $(target).offset().top - 50
            }, {
                duration: 1000,
            });

            $('body').scrollspy({ target: '#navbar-example2', offset: $(target).offset().top });
            $(this).parent().addClass('active');

            return false;
        });
    });

    // Navbar fixed position
    var distance = $('#site-header').offset().top,
        $window = $(window);

    $window.scroll(function() {
        if ( $window.scrollTop() >= distance ) {
            $('#site-header').addClass('fixed-nav')
        }
        if ( $window.scrollTop() <= distance ) {
            $('#site-header').removeClass('fixed-nav')
        }
    });

    $('body').scrollspy({ target: '#navbar-example2', offset: 0 });
</script>

I am currently at a roadblock and struggling to pinpoint where I might be going wrong. Despite attempting various CSS tweaks, I still can't get it to work. Any assistance or suggestions would be greatly appreciated.

Answer №1

Update the jQuery selector in the click handler to...

$(".nav-link,.dropdown-item").click(function() {
  ...
});

https://www.example.com/code

The issue with using the nav-link selector is that it lacks an href attribute, causing the click event to not be triggered. Additionally, consider making the Navbar fixed-top to prevent it from scrolling away when navigating to a specific section.

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

Does the responsive navigation vanish when the size is changed?

I've encountered a glitch with my responsive drop-down navigation that's affecting its functionality. Here's the scenario: when the page loads, everything works fine. But if I resize the page to reveal the mobile nav (hamburger menu), it be ...

Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive? I have implemented a custom file directive for this purpose. The Directive: app.directive('ngFileModel', ['$parse', function($parse) { return { ...

Can we bring flexbox inserts, removes, and item positioning to life through animation?

This question was first raised in 2012, but the responses provided didn't address my specific situation (smooth transition for rearranging wrapped content). "After removing an item from a flexbox, the remaining items snap into their new positions imm ...

Alert: The container is empty and has no defined length

Can anyone provide guidance on how to properly implement this code? I am using a mustache template where I want to display an alert message that says "no matches" or "matches are available" based on the data. The else statement works fine, but the if state ...

The route function is not being executed

I'm currently developing a straightforward restaurant web application that utilizes a mongo-db database to manage the menu items. The problem lies with my client js file, which is supposed to utilize a routing function to access the database and retri ...

Resolving unexpected behavior with res.locals and pug integration

I have a function in my app.js that allows the user-id to be accessible in pug templates. app.use(function (req, res, next) { res.locals.currentUser = req.session.userId; next(); }); When logged in, I can access the id. However, when not logged in, t ...

Having trouble accessing the value of an item in a dropdown box on a website

I am currently developing a webpage using HTML5 and Knockout Js. I am facing an issue where I am unable to retrieve the ID of the selected item from a dropdown box in order to insert a value into an SQL table. As an example, consider the following SQL tab ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

How can I avoid OnServerClick when using OnClick?

Currently, I am working with ASP.NET and have a link that utilizes both onclick and onserverclick events. While both are crucial, I would like the onclick event to override the onserverclick event if possible. This is the code snippet I am currently exper ...

Webpack 5 and Shakapacker 7: Struggling to Initialize jQuery

Upon upgrading from webpack 4.46.0 to webpack 5.88.2 and shakapacker 7.0.3 within Rails 6.1.7.6, an error stating Uncaught ReferenceError: $ is not defined appeared. Below is the current configuration: package.json { "name": "app", "private": true, ...

The message appearing on my screen reads: "Attempting to read properties of an undefined value, specifically 'map'."

I am attempting to create a map of my various people, but I keep encountering an error with the title. I'm having trouble understanding where the issue lies, here is my code snippet: export const Testt = ({ childs}) => { console.log(childs) ...

Update the state with the currently selected item from the dropdown menu

var Example= React.createClass({ handleSelect: function(e) { this.setstate({ selectedItem: e.currentTarget.text }) }, render: function() { return <select onChange={this.handleSelect.bind(this)}> <option value="1">Item 1</ ...

Creating a thumbnail with a close button using an image

My code is available at the following link: https://codepen.io/manuchadha/pen/PBKYBJ In this form I have created, I am trying to implement an image upload feature using a file input. The goal is to display a thumbnail of the selected image below the file ...

Checking if a Vector3 is visible within a camera's field of view using three.js

Is there a simple and cost-effective way to determine if a point or Vector3 is within the field of view of a camera using three.js? I would like to create a grid of boxes to cover the "floor" of a scene, but only up to the edges of the visible area, witho ...

Javascript Error: Missing Object (SelectedIndex Property)

Struggling to find a solution for the mysterious "Object Expected" error that keeps popping up. Currently working on a concert attendance form page where users input their information. The pesky error is showing up in my function "totalBill," specifically ...

Background image of HTML Iframe element does not display - Inline style block

https://i.stack.imgur.com/JW26M.png After setting the iframe's innerHTML using this line of code: iframedoc.body.innerHTML = tinyMCE.activeEditor.getContent(); The styles for the elements within the iframe are contained in an inline style block. Ho ...

Creating a dynamic slideshow with automated arrow navigation is simpler than you may think

I have successfully tested the slideshow and it is functioning perfectly without any issues. I would like to have a dual slideshow setup (slideshow 1 and slideshow 2) with next and previous buttons, but I am interested in adding an automatic sliding featur ...

Is it possible for my Java Applets to be compatible with Chrome 45?

Our web application utilizes three Java Applets for various functions. We are aware that Chrome 45 will no longer support NPAPI. Upon visiting Oracle's page, it is stated that Java Plugin depends on NPAPI. I have tested my Applets on Chrome 43 and 4 ...

The global installation of grunt was unsuccessful and I am unable to locate it on npmjs.org

Can anyone help me troubleshoot this error I'm encountering while running npm install? I usually don't have issues installing libraries globally, but I can't seem to find grunt on npm install -g grunt npm ERR! Error: Not found: grunt@&apos ...

Vue Material - Effortlessly integrate native transitions within router views

In the project I'm currently working on, I have chosen to use Vue Material for the development of a single-page application. The approach I am taking follows a common trend in which a central "container" component is utilized to manage the shifting vi ...