Is there a way to prevent Bootstrap offcanvas from causing the website to scroll?

Utilizing a Bootstrap offcanvas for a <nav> menu on a mobile site, I aim to navigate users to specific sections of the website when they click on a <li>. I've implemented a simple JavaScript script that triggers the offcanvas exit button and then uses an ID to scroll the user to the designated section. However, an issue arises where the offcanvas scrolls the website back to its original position.

The functionality works as intended until the button regains focus or another event triggers a scroll back to the top where the button is located.

Upon investigation, I've discovered that Bootstrap adds an 'open-modal' class to the body when using modals, and I assume a similar class is added when using offcanvas, which may interfere with scrolling. I've also learned that removing the

data-bs-toggle="offcanvas"
attribute can help when creating elements dynamically with JavaScript, but that is not the case here. How can I resolve this issue and achieve the desired effect on the site? Below is the JavaScript file and the HTML for the <nav>.

JAVASCRIPT:

function ServicePackages(){
    const exitBtn = document.getElementById('button-close');

    exitBtn.click();

    window.location.href = "#service-packages";   
}

// Repeat similar functions for other sections...

function Home(){
    const exitBtn = document.getElementById('button-close');

    exitBtn.click();

    window.location.href = "#home";
}

HTML:

<nav class="navbar navbar-expand-lg bg-light">
        <div class="container-fluid">
            <a class="navbar-brand" href="javascript: return false">
                <img class="d-inline-block align-text-bottom" src="assets/logo.png" width="156px" height="45px">
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#navModal"
                aria-controls="offcanvasRight">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="offcanvas offcanvas-end" tabindex="-1" id="navModal" aria-labelby="offcanvasRightLabel">
                <div class="offcanvas-header">
                    <img class="offcanvas-title d-inline-block align-text-bottom" src="assets/logo.png" width="156px"
                        height="45px">
                    <button id="button-close" class="btn-close" type="button" data-bs-dismiss="offcanvas"
                        aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <script src="modal.js"></script>
                    <ul class="navbar-nav justify-content-end flex-grow-1 pe-3">
                        <li class="nav-item">
                            <a class="nav-link" onclick="ServicePackages()" aria-current="page"
                                href="#service-packages">SERVICE
                                PACKAGES</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" onclick="IndividualServices()" aria-current="page"
                                href="#individual-services">INDIVIDUAL
                                SERVICES</a>
                        </li>
                        // Repeat similar <li> elements for other sections...

                        <li class="nav-item">
                            <a class="nav-link active" onclick="Home()" aria-current="page" href="#home">HOME</a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

Answer №1

Initially, my approach would involve eliminating the window.location.href = statement from all functions since the hrefs are already linked to the anchor tag in the HTML.

If this does not yield any results, my next step would be to address the overflow issue by incorporating the following snippet at the beginning of the document:

<style>
  body {overflow:hidden}
</style>

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

Passing a PHP variable through a URL using the GET method

I need to pass a value using the get method. The code snippet is as follows: <td><a href="cart-remove.php?id={$row['id']}" class="remove_item_link"> Remove</a></td> The value I want to send is stored in $row['id&a ...

The jQuery slider's next button is not functioning as intended

jQuery('#slider-container').bjqs({ 'animation' : 'slide', 'width' : 1060, 'height' : 500, 'showControls' : false, 'centerMarkers' : false, animationDuration: 500, rotationS ...

Getting rid of the excess white space below the footer caused by concealed elements

In my design, I have three columns. The rightmost column is filled with 'Divs' containing collapsed information that can be scrolled through using the mouse wheel. The overflow in the center is hidden. The width of all three columns is set to 760 ...

Guide to seamlessly integrating form data into MySQL using JavaScript and HTML without redirecting the user from the current page

Having trouble inserting a new user into MySQL database? I've attempted using both jQuery and pure JavaScript, but it doesn't seem to be working. There's no response when I click on the submit button. Any ideas on what might be causing this ...

I need help getting rid of the unwanted text and objects that are appearing on my website

I recently designed a basic website and everything was running smoothly until I decided to insert a new ul division in the HTML page as a spacer between two elements: <div> <ul> <li><a></a></li> </u ...

The width of mat-table columns remains static even with the presence of an Input field

I'm currently working on an Angular component that serves the dual purpose of displaying data and receiving data. To achieve this, I created a mat-table with input form fields and used {{element.value}} for regular data display. Each column in the tab ...

What impact do media queries have on scaling web pages?

Why does the page scale change with media queries? @media only screen and (min-width: 500px) { body { background-color: blue; } } @media only screen and (min-width: 800px) { body { background-color: green; } } @media only screen and (min-width: 1000px) ...

In React hooks, Socket.io has a strange behavior where it adds users multiple times with varying socket IDs

Encountering an issue with my React and Socket.IO application. Upon a user joining a room, their information is being duplicated in the client's array on the client side. Despite having the same username, the entries have different socket IDs assigned ...

Transferring $scope information to resolve in $stateProvider.state

In the app.teams.show parent state, "team" is stored in $scope.data.team. From within a controller, I can access $scope.data.team and thus $scope.data.team.organization_id. The question is: How can I retrieve $scope.data.team.organization_id from inside t ...

Ensure that the child div remains at the bottom of the parent div

I'm trying to make sure that the subfooter div stays at the bottom of the childbox div like a footer. You can see the code on this jsfiddle link <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title ...

What is the optimal approach for managing multiple languages using React Router version 5?

I am exploring the possibility of incorporating multiple languages into my website using React and React Router v5. Can you provide guidance on the most effective approach to achieve this? Below is a snippet of the current routing code I am working with: ...

What is the best way to iterate through data within a view while showcasing information retrieved using AngularJS?

As I start my journey into learning AngularJS, I am looking for some guidance from those who have experience with it. Although I am proficient in JavaScript/jQuery, I am finding it challenging to grasp the fundamentals of AngularJS at the moment. My query ...

What's the reason the element inside the <div> is not displayed when a value is selected in the dropdown box?

I am perplexed as to why the element inside the does not appear when a value is selected in the drop down box. However, it works perfectly fine in JSFiddle: JSFiddle Below is my HTML code and Jquery script that functions properly in my own system: <t ...

Passing data through events from a parent component to a child component in Vue.js using the $emit method

Having trouble making this work! I have included the $emit code in my click event to trigger a custom event. <h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="$emit('addBusinessHours', null)"> ...

Error: ...[i] has not been defined

What seems to be the issue with this part of the script: function refreshLabels() { // loop through all document elements var allnodes = document.body.getElementsByTagName("*"); for (var i=0, max=allnodes.leng ...

Tips for creating a div element that closes on the second click:

On the PC version, I have three blocks that open and close perfectly when clicked. However, on the mobile version, when I click on one block, it opens but does not close unless I click on another block. Additionally, if I click again on the same block th ...

problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet: const response = await fetch(' ...

"Preventing Cross-Origin Requests" error encountered while trying to load a JSON document

I've been working on an online experiment using JavaScript, and I need to load parameters for the task from a JSON file. I managed to do this successfully when running the task through a live server. However, if I try to run it locally by opening the ...

Tips for detecting when the MDC Snackbar has been closed using JavaScript

I'm currently working with Material Design's Snackbar in combination with VueJS. My goal is to detect when the snackbar has finished closing. The Snackbar object does have a property called isOpen, which allows me to check if the snackbar is ope ...

Enforce a restriction on the user's input value for the amount field within a React application

I'm looking to limit the user from entering more than 50000 in the input value. How can I achieve this using React? I am currently handling this on the onchange event. onPaymentAmountChanged = (e) => { let inputValue = e.target.value; if (i ...