What is the best way to synchronize the scrolling of a container element with scrollspy?

In my layout, I have multiple sections with a scrollbar that displays buttons using scrollspy. Everything is working perfectly except for one issue - when scrolling too far down, the scrollspy disappears off the page to the right. Is there a way to adjust the scrollbar so that it moves in the direction of the active scrollspy button (the active button receives a class active automatically)?

It's important to note that I am not utilizing jQuery in this project.

Below is the code snippet:

window.setInterval(function(){
  window.onload = function () {
        document.getElementsByClassName('navbar')[0].scrollLeft = 0;
        var menus = document.getElementsByClassName('nav-link');
        for (var i = 0; i < menus.length; i++) {
            if (menus[i].classList.contains('active')) {
                document.getElementsByClassName('navbar')[0].scrollLeft = menus[i].offsetLeft;
            }
        }
    }
}, 1);

Thank you for your assistance!

Answer №1

To enable smooth scrolling of the navbar to the active scrollspy button, you can create a scroll event listener with a function. Additionally, adding scroll-behavior: smooth in the navbar CSS will prevent sudden scrolling.

const nav = document.querySelector('nav');
const h = document.documentElement;

document.addEventListener('scroll', function() {
  nav.scrollTo(nav.querySelector('.active').offsetLeft, 0);
});
<!doctype html>
<html>
...
  <script>
    var scrollSpy = new bootstrap.ScrollSpy(document.body, {
      target: '#navbar-example'
    })
  </script>
</body>

</html>

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

AngularJS scope variable not getting initialized inside promise

I've encountered an issue with my code while using CartoDB. The goal is to execute a query using their JS library and retrieve some data. The problem arises when I attempt to assign the result as a scope variable in AngularJS, after successfully worki ...

Have the functionality of right clicking and selecting Paste work in the input field using style=text and a button

Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#submit').prop('disabled', true); $('#links').change(function() { $('#submit').prop('disabled ...

I am looking for a way to connect a saved phone number with a Vue tel input so that I can make changes

Currently, I am utilizing vue-tel-input to input a phone number. Below is the code snippet: <template> <div> <vue-tel-input v-model="client.ClientPhone" v-bind="bindPropsUserInfo"></vue-tel-input> </div> ...

Is it possible to style an element that has extended beyond its parent container using CSS?

Is it possible to select items that have a float:right property and appear on the next line due to reasons like excessive content on the left or a window size too small? This is necessary because the parent item has a background image that looks good, but ...

Steps for showcasing each element of an array separately upon a mouse click

I am working on a website where each click on the screen reveals a new paragraph gradually. I plan to organize these paragraphs in an array and display them one after the other in sequential order upon user interaction. The challenge lies in combining thes ...

I am unable to utilize the map function as it results in a TypeError: The property 'map' is undefined and cannot be read

I recently delved into the world of "REACT" in order to work on the front-end of my own project. I encountered a problem for 2 days with the map function while getting data from my back-end and saving the IDs in the Cuartos array. I couldn't figure ou ...

Oops! Looks like there's an issue with the NextJS Custom Carousel bug. The error message reads: ReferenceError: document is not defined and is unable to read properties of undefined (

I have developed a unique carousel component to showcase text testimonials from scratch. The custom carousel utilizes a specialized script, carouselFunction.js, for navigational functionality to cycle through each testimonial. Here is an image of the carou ...

Guidelines on incorporating HTML files as templates into Rollup and compiling them into concatenated strings

I am currently working on setting up a build process for Optimizely experiments using Rollup instead of Webpack. The reason for this change is that the code exported by Webpack is too bloated for our specific use case. My goal is to import .html files as t ...

Retrieve a JSON object by making a request to a URL with specific parameters

Struggling with a common coder's mental block: The idea: Imagine entering a URL like www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345 Rather than receiving a webpage, the goal is to get back a json object for parsing on anoth ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

Can a variable be initialized with a concealed or additional argument?

After just 2 weeks of coding, I'm struggling to find information on how to initialize a variable with an extra argument in a recursive function call. Is this even possible? And if it is, are there any scenarios where it's considered best practice ...

Utilize a DIV element to apply a class to CKEditor

Currently, I am utilizing CKEditor in DIV mode instead of an IFRAME and I am facing a challenge in assigning a class to the editor itself. While I have managed to add classes to elements within the editor, figuring out how to assign one to the editor itsel ...

How can I securely save a user's login information using ExtJS without saving it multiple times?

Currently, I am utilizing Ext.Ajax.request() to access a PHP page that provides user-specific information during the login process. In order to store variables such as cookies and session information in ExtJS, I have created a model with necessary fields a ...

Discovering the way to retrieve background height following a window resize using jQuery

Is there a way to obtain the background height once the window has been resized? div { background-image: url(/images/somebackground.jpg); background-size: 100% 90%; background-repeat: no-repeat; width: 70%; background-size: contain; ...

Netlify is failing to recognize redirect attempts for a Next.js application

After successfully converting a react site to utilize next.js for improved SEO, the only hiccup I encountered was with rendering index.js. To work around this, I relocated all the code from index to url.com/home and set up a redirect from url.com to url.co ...

Guidelines for incorporating a router into the title of a Vuetify.js toolbar

I am currently utilizing vuetify.js in my project and I encountered an issue. I wanted the application title to link to the top menu, but when navigating to /route shop and /discount, the HogeHoge button's state changed unexpectedly. Is there a soluti ...

Determining the spatial location of an object in Three.js in relation to the camera for the purpose of creating a trail

In my scene, I have an object (a pen) that rotates around its axis in the render loop using the following code: groupPen.rotation.y += speed; groupPen.rotation.x += speed; Additionally, I have a TrackballControls that allows the user to rotate the entire ...

Is there a way to iterate through objects and add new properties to them?

I am trying to achieve the following object: let newPost = { title: "Post 1", Content: "New content" } with the code below: let newPost = {}; let postData = $(".post-data").each (function(index) { newPost.title = $ ...

CSS for the root folder of an ASP.NET website

After deciding to venture into ASP.NET, I quickly encountered my first obstacle. The folder structure is as follows: \ ->Admin -->Admin.Aspx ->CSS -->Style.css ->Images -->bg.gif Default.aspx Default.master Both admin.aspx and ...

Navigation bar with a full-page slider

I am trying to incorporate my bootstrap nav bar into a full-width slider, similar to the layout in this example. https://i.sstatic.net/LE9wP.jpg This is the full width slider http://codepen.io/grovesdm/pen/MazqzQ Currently, I have positioned the nav ba ...