Prevent scrolling through a fixed, scrollable div using the mousewheel

I am encountering an issue on my webpage where I have a fixed y scrollable sidenav and a main body. The problem arises when scrolling with the mouse wheel while the pointer is inside the side nav, causing the body to scroll depending on the element's position. This issue is due to the margin of the main body still overlapping with the side nav because of Bootstrap offset such as offset-md-3.

https://i.sstatic.net/svXqe.png https://i.sstatic.net/imWAT.png

I am seeking a solution to prevent the main body from scrolling when the mouse is on the sidenav without using any plugins. I specifically require a solution using jQuery and Bootstrap 4 only.

Initially, I thought of fixing the issue like this, but changing to fixed caused the main body to snap back to the top.

I tried disabling scrolling on hover over the .SideNav, but I needed to keep the scrollbar for consistency.

$(".SideNav").hover(function () {
        $('body').css({
            "position": 'fixed',
            "overflow-y": 'scroll'
        });
    },
    function () {
        $('body').css({
            position: 'inherit',
            "overflow-y": 'scroll'

        });
    });

Answer №1

At first, the use of fixed positioning was causing the content to jump back to the top of the page during scrolling. To address this issue, I had to make adjustments like this:


    var offset;
    $(".SideNav").hover(function () {
        offset = window.pageYOffset  // Get offset to set position when fixed
        $("main").css("position", "fixed");
        $('body').css({
            "position": 'fixed',
            "overflow-y": 'scroll',
            "top": 0 - offset
        });
    },
    function () {
        $("main").css("position", "inherit");
        $('body').css({
            "position": 'inherit',
            "overflow-y": 'scroll'
        });
        $(window).scrollTop(offset);  // Restore original position when scroll bar returns
    });

Answer №2

I found the situation quite intriguing and after reading your response, I couldn't help but wonder why you deemed it necessary to make adjustments to both the position and top properties. It appears that these changes may have been essential in order to align with the specific HTML and CSS structure you are working with.

In any case, I wanted to offer an alternative approach in a simpler or more minimalist setting. Please feel free to share your thoughts:

var currentOverflow;
$(".SideNav").hover(()=> {
    currentOverflow = $('body').css('overflow');
$('body').css({
    overflow: 'hidden'
    })
},
() => {
    $('body').css({
    overflow: currentOverflow
})
});
    
.SideNav{
position: fixed;
height: 100vh;
width: 20vw;
background: red;
top: 0;
left: 0
}
span{
margin-left: 30vw
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="SideNav" id="fixed"></div>
        <br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a... (truncated for brevity) ...span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span><br><span>a</span>

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

Plugin for jQuery that paginates text when it overflows

Looking for a solution here. I have a fixed width and height div that needs to contain text. If the text exceeds the size of the div, I want it to paginate with dots at the bottom of the page indicating each page, similar to slideshow functionality. Are t ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Ways to verify the presence of a key within an array of objects

I'm on a mission to determine whether a specified key exists in an array of objects. If the key value is present, I need to return true; otherwise, false. I enter the key into a text box as input and then attempt to check if it exists in the array of ...

Tips for choosing a component without including its subcomponents

I need help selecting an element using jQuery while excluding one of its children: <div class="parent-that-jQuery-should-find"> <div class="child-to-be-excluded"> <p></p> </div> <div class="child-not-to-be-excl ...

What is the best way to change the active class using jquery?

Excuse me, can I get some help? I'm still learning html and jquery, and I've seen this question asked before, but none of the solutions seem to work for me. I'm trying to change the active class in my navbar when I click on another link. Wh ...

obtain the final result once the for loop has finished executing in Node.js and JavaScript

There is a function that returns an array of strings. async GetAllPermissonsByRoles(id) { let model: string[] = []; try { id.forEach(async (role) => { let permission = await RolePermissionModel.find({ roleId: role._id }) ...

What is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

Incorporate image into Vue.js form along with other information

I have been successfully sending the content of multiple fields in a form to the Database. Now I am looking to add an additional field for uploading images/files and including it with the other form fields, but I am unsure about how to accomplish this task ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

What are the special characters in .NET?

Can the characters in .NET be unescaped? Is there a way? I need to send a string containing PHP code via ajax to a .NET method. However, when this method sends it via email, the characters have been escaped in jQuery, resulting in the code looking like t ...

Encountered an issue when attempting to save data to the database using an AJAX request in Symfony 3

i need to input text in a form and store it in my database as well as display it on my view using jQuery. here is the input form: <div class="panel rounded shadow"> <form method="post"> <textarea id="txt" class="form-control in ...

Customizing tooltips in Highcharts donut charts with detailed drilldown information

My goal is to insert formatted html into the tooltips of the outer donut ring, using data from the drilldown section. Here's an example: data = [{ y: 33.84, color: '#ff0000', drilldown: { name: 'Downloads', ...

Learn how to display a "not found" message in a React.js application

I have a piece of code where I am sending a post request to an API and retrieving all the data from the API in a table. I am trying to find currency data based on the currency name, if found I display the data in a div, if not found I want to print "not ...

Can we find a different way to address this issue with a "functional programming" mindset that doesn't involve utilizing the `forEach` method?

There has been a discussion about whether or not we still need to use forEach in JavaScript due to the availability of new language features. Some have suggested that this shift is an indirect push towards functional programming. I recently came across an ...

Angular JS manifesting a nested JSON filter system

As a newcomer to AngularJS, I am trying to implement a filter in my ng-repeat. Here is the structure of my JSON data: var data = [ {name:test1,b1:{lastValue:0},b2:{lastValue:6},b3:{lastValue:6},b4:{lastValue:0}} {name:test2,b1:{lastValue:6},b2:{l ...

In the Twitter Bootstrap documentation, which element is utilized for the sidebar?

I'm curious about the most efficient method for creating a sidebar like this using Bootstrap 4. https://i.sstatic.net/3eKwN.png From what I can see, it appears to be a custom component designed specifically for the documentation page, rather than ...

WebDriver encounters difficulty clicking on a certificate error popup window

Currently, I am using webdriver 2.40.0 in C# to interact with my company's website. The issue arises when I encounter a certificate error page while trying to access certain elements. Specifically, after clicking the override link and entering some in ...

Is it possible to pass an AngularJS ng-form object as a parameter in ng-if?

When I try to preview, the save button in my preview mode remains enabled. You can view the code snippet here: http://plnkr.co/edit/I3n29LHP2Yotiw8vkW0i I believe this issue arises because the form object (testAddForm) is not accessible within the ng-if s ...

Changing knockoutJS foreach binding dynamically

I have a list of arrays known as table#1, table#2, ... table#10 and I want to be able to click on a table number and display the list items of that table in a panel. Here is a snippet of the code: The HTML part works fine. The only issue lies in this li ...

There seems to be an error with JVectorMap: the <g> attribute transform is expecting a number but is instead receiving "scale(NaN) translate(N..."

Hey there! I'm currently working on creating a form with a map to select the country of birth using JVectorMap. However, when checking the Google Chrome developer console, I encountered the following error message: jquery-jvectormap-2.0.5.min.js:1 Err ...