When closing the menu in Bootstrap, the page automatically scrolls back to the top

Whenever I open my menu, click on a link, and scroll down the page using the menu, upon closing the menu I am automatically taken back to the top of the page.

I have experimented with the following scripts:

let y = window.scrollY;
let offcanvas = document.getElementById('offcanvasMenu');
offcanvas.addEventListener('hidden.bs.offcanvasMenu', (e) => {
   window.scrollTo(0, y);
});

and

var myOffcanvas = document.getElementById('offcanvasNav')
myOffcanvas.addEventListener('hide.bs.offcanvas', function (e) {
    console.log(e)
    //e.preventDefault()
    //e.stopPropagation()
})

Unfortunately, none of these scripts have provided a solution for my issue.

Code Snippet

<a class="bi bi-list offcanvas-icon" data-bs-toggle="offcanvas" href="#offcanvasMenu" role="button" aria-controls="offcanvasMenu"></a>

<div class="offcanvas offcanvas-end" data-bs-scroll="true" tabindex="-1" id="offcanvasMenu" aria-labelledby="offcanvasMenuLabel">
  <div class="offcanvas-header">
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>

  <div class="offcanvas-body d-flex flex-column justify-content-center align-items-center">
    <nav>
      <ul>
        <li>
          <a href="#contacts">Contacts</a>
        </li>
      </ul>
    </nav>
  </div>
</div>

<section class="contact-widget spad" id="contacts">lala </section>`

<!-- Bootstrap 5 + icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/dist/js/bootstrap.bundle.min.js"></script>

Answer №1

Here's a clever solution:

The issue arises when the hide.bs.offcanvas event triggers, causing the scrolling to jump back to the navigation prematurely. To address this, you can insert a snippet of code that maintains the current scroll position.

Your JavaScript code should look like this:

    let myOffcanvas = document.getElementById('offcanvasMenu');

    myOffcanvas.addEventListener('hide.bs.offcanvas', function (e) {
        let currentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;

        setTimeout((() => {
            document.documentElement.scrollTop = document.body.scrollTop = currentScrollTop;
        }), 310);
    });

Essentially, the script captures the scroll location before the page jumps back to the top and then smoothly transitions back to it after a delay of 310 ms. The ideal time delay may vary. In this example, 300 works well. Increasing this number will also work, but may result in noticeable bouncing from the top to the current position. Conversely, a lower number may not be as effective.

Below is a functioning demo:

    let myOffcanvas = document.getElementById('offcanvasMenu');

    myOffcanvas.addEventListener('hide.bs.offcanvas', function (e) {
        let currentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;

        setTimeout((() => {
            document.documentElement.scrollTop = document.body.scrollTop = currentScrollTop;
        }), 310);
    });
<a class="bi bi-list offcanvas-icon" data-bs-toggle="offcanvas" href="#offcanvasMenu" role="button" aria-controls="offcanvasMenu"></a>


<div class="offcanvas offcanvas-end" data-bs-scroll="true" tabindex="-1" id="offcanvasMenu" aria-labelledby="offcanvasMenuLabel">
  <div class="offcanvas-header">
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>

  <div class="offcanvas-body d-flex flex-column justify-content-center align-items-center">
    <nav>
      <ul>
        <li>
          <a href="#contacts">Contact</a>
        </li>
      </ul>
    </nav>
  </div>
</div>

<br>
<br>
... // Additional content
<br>

<section class="contact-widget spad" id="contacts">Contact Section</section>

<!-- Bootstrap 5 + icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.0/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>

Note: I purposely inserted multiple <br> tags for visualization purposes.

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

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

interrupt the node script using async behavior

I encountered an issue while running the npm install command to install a list of modules on Node, specifically related to async. TypeError: undefined is not a function What could be causing this problem? var fs = require( "fs" ), path = require( ...

A unique Javascript feature that switches the text on various buttons

As someone who is relatively new to Javascript and web development, I am currently working on a project that involves creating multiple text areas for users to input and save text. Each text area is accompanied by a button with a unique ID that functions a ...

The code for 'infinite scroll' is currently only functional for scrolling at the top

I have implemented a piece of JavaScript code that is supposed to detect when the user has scrolled to the bottom of the document: $(window).scroll(function() { if ($(window).scrollTop() == $(document).height() - $(window).height()) { ...

After a period of time, NodeJS abruptly crashes while processing a CSV file

Recently, I've been working on a project that involves converting CSV data into XML. To accomplish this, I have been using the fs.createReadStream() method to read the CSV file. However, I encountered an issue where the terminal crashes unexpectedly a ...

What steps do I need to take to share my Node JS application on my local area network (

I have a Node.js application running on my Ubuntu machine successfully, as I can access it through localhost:8080. However, other machines on the network are unable to reach it. CODE: const portNumber = 8080 let app = express() app.use(express.static(__d ...

Is there a way to imitate a method that initiates an AJAX request?

I am currently working on writing tests for my Angular application and I need to mock a method in order to avoid making actual requests to the server. Within my grid.service.ts file, here is the method I am trying to mock: loadAccountListPromise(id: str ...

How should event listeners be unbound and child elements removed in single page applications?

I've recently delved into the world of memory leaks in JavaScript while working on a large single-page application. After using Chrome's Profiles (Snapshot) function, I noticed an abundance of detached DOM elements indicating a possible memory le ...

D3.js: Difficulty fitting the chart within my bootstrap div

Currently, I'm encountering a problem where the "card" component from Bootstrap is not adjusting responsively with my d3.chart. The screenshot below displays the outcome: https://i.sstatic.net/2MhBx.png Chart Code const sample = [ { languag ...

Dragging and dropping elements using Jquery to various positions on the screen

I am working on a project with draggable buttons and a droppable textarea. When I drag a button onto the textarea, it displays some code. If I drag another button, the text related to that button is added to the existing code. My query is how can I insert ...

Need help with decoding XML namespaces?

How can I use JavaScript/Ajax to parse values from the following XML snippet? <yweather:astronomy sunrise="6:34 am" sunset="8:38 pm"/> I've been attempting to retrieve the sunrise attribute with no success using this code: var response = tran ...

Tips for implementing a button redirection to a different page using React

I am facing an issue with a component that includes a function onClick in its Class.propTypes: onClick: PropTypes.func Within another component, I have used this particular component multiple times to populate a page. Each instance of these components con ...

Troubleshooting issue: Inability to assign classes to child elements within divs of a designated class

Currently, I am facing an issue while attempting to insert divs into multiple divs that share a common class called ".description". My goal is to assign a unique class to each internal div, but for some reason, this only seems to work for the first div w ...

Print out the error message: "ERROR [ExceptionsHandler] Unable to access the property 'log' as it is undefined."

Just starting out with Nestjs and JavaScript but ran into an error when trying to print a text line using console.log() const my_text ="123" console.log(my_text) https://i.sstatic.net/xPnzX.png ...

After refreshing the compiler, the .toggleClass() method in React jQuery finally functions properly

I've been working on creating a sideboard for my react application and found this helpful example: https://codepen.io/illnino/pen/nwPBrQ. However, I've encountered an issue that I can't seem to solve on my own. What is the exact problem I&a ...

Issues with webpage responsiveness, width not adjusting correctly

Just completed coding my website and now I'm facing a new challenge. I am focusing on making it responsive for tablet screens (768px) starting with the header section, but for some reason, the modifications I make in the responsive.css file are not ta ...

Why Does Angular's ngIf Always Result in a Negation to True?

Can someone please clarify this for me? I'm having trouble understanding why the *ngIf condition and else statement always evaluate to true unless I am completely mistaken. Here is the situation: I have an icon that should turn the background color t ...

Is GetStaticPath in NextJS suitable for generating large amounts of static data?

On my website, I have a page dedicated to displaying information about hotels based on their unique IDs. To achieve this functionality, I utilize getStaticPath to generate paths like /hotel-info/542711, where 542711 represents the hotel's ID. However ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

Tips for navigating upwards to a specific element and successfully clicking on it in Selenium

I am facing a situation where the system needs to scroll upwards to reach the web element located in the left panel of the page and then click on it to proceed with other operations. I have attempted various methods but none seem to be effective. Can anyon ...