Stop the page from scrolling when scrolling within a specific DIV to address the [Violation] warning appearing in the console

Initially, it may seem like a duplicate question that has been answered here, but there are additional aspects that need to be addressed.

How do I resolve the following [Violation] warning in the Google Chrome console?

[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking the event handler as 'passive' to make the page more responsive.

Here is a code snippet that works but triggers the aforementioned [Violation] warning.

$.fn.isolatedScroll = function() {
  this.on('mousewheel DOMMouseScroll', function (e) {
    let delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
      bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
      topOverflow = this.scrollTop <= 0;

    if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
      e.preventDefault();
    }
  });
  return this;
};

$('.js-isolated-scroll').isolatedScroll()

// No need to check here as it's just repeating <p> tags
function multiplyNode(node, count, deep) {
  for (var i = 0, copy; i < count - 1; i++) {
    copy = node.cloneNode(deep);
    node.parentNode.insertBefore(copy, node);
  }
}

multiplyNode(document.querySelector('.p-in-fixed'), 20, true);
multiplyNode(document.querySelector('.p-in-body'), 20, true);
body{
  position: relative;
  background-color: #ccc !important;
  padding: 20px 20px 20px 50%;
}
.fixed {
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  padding: 20px;
  overflow: auto;
  position: fixed;
  border: 1px solid #333;
  width: calc(50% - 40px);
  background-color: #f8f8f8;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="js-isolated-scroll fixed">
  <p class="p-in-fixed">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab accusamus aliquam, beatae blanditiis, cum dicta earum eligendi esse eum inventore iusto molestiae necessitatibus nesciunt praesentium quod ratione, similique sit voluptates.</p>
</div>

<p class="p-in-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab accusamus aliquam, beatae blanditiis, cum dicta earum eligendi esse eum inventore iusto molestiae necessitatibus nesciunt praesentium quod ratione, similique sit voluptates.</p>

I attempted to fix this using Modernizr's passiveeventlisteners by using this code

Modernizr.passiveeventlisteners ? {passive:true} : false
while following an answer provided here. However, I encountered this error message in the console:

Unable to preventDefault inside passive event listener invocation.

It is evident that I cannot use e.preventDefault() when using {passive:true}, which makes sense. I simply want to know how I can prevent page scrolling when scrolling a DIV while also resolving the [Violation] warning in the console.

Below is the code snippet that does not work and results in the error mentioned above.

document.getElementById('fixed-content').addEventListener('wheel', avoidBodyScroll, Modernizr.passiveeventlisteners ? {passive:true} : false);
document.getElementById('fixed-content').addEventListener('mousewheel', avoidBodyScroll, Modernizr.passiveeventlisteners ? {passive:true} : false);
document.getElementById('fixed-content').addEventListener('DOMMouseScroll', avoidBodyScroll, Modernizr.passiveeventlisteners ? {passive:true} : false);

function avoidBodyScroll(e) {
  let delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
    bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
    topOverflow = this.scrollTop <= 0;

  if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
    e.preventDefault();
  }
}

// Nothing to check here as it's just repeating <p> tags
function multiplyNode(node, count, deep) {
  for (var i = 0, copy; i < count - 1; i++) {
    copy = node.cloneNode(deep);
    node.parentNode.insertBefore(copy, node);
  }
}

multiplyNode(document.querySelector('.p-in-fixed'), 20, true);
multiplyNode(document.querySelector('.p-in-body'), 20, true);
body{
  position: relative;
  background-color: #ccc !important;
  padding: 20px 20px 20px 50%;
}
.fixed {
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  padding: 20px;
  overflow: auto;
  position: fixed;
  border: 1px solid #333;
  width: calc(50% - 40px);
  background-color: #f8f8f8;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
  /*! modernizr 3.5.0 (Custom Build) | MIT *
  * https://modernizr.com/download/?-passiveeventlisteners-setclasses !*/
  !function(e,n,s){function o(e,n){return typeof e===n}function a(){var e,n,s,a,t,f,l;for(var c in r)if(r.hasOwnProperty(c)){if(e=[],n=r[c],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(s=0;s<n.options.aliases.length;s++)e.push(n.options.aliases[s].toLowerCase());for(a=o(n.fn,"function")?n.fn():n.fn,t=0;t<e.length;t++)f=e[t],l=f.split("."),1===l.length?Modernizr[l[0]]=a:(!Modernizr[l[0]]||Modernizr[l[0]]instanceof Boolean||(Modernizr[l[0]]=new Boolean(Modernizr[l[0]])),Modernizr[l[0]][l[1]]=a),i.push((a?"":"no-")+l.join("-"))}}function t(e){var n=l.className,s=Modernizr._config.classPrefix||"";if(c&&(n=n.baseVal),Modernizr._config.enableJSClass){var o=new RegExp("(^|\\s)"+s+"no-js(\\s|$)");n=n.replace(o,"$1"+s+"js$2")}Modernizr._config.enableClasses&&(n+=" "+s+e.join(" "+s),c?l.className.baseVal=n:l.className=n)}var i=[],r=[],f={_version:"3.5.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var s=this;setTimeout(function(){n(s[e])},0)},addTest:function(e,n,s){r.push({name:e,fn:n,options:s})},addAsyncTest:function(e){r.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=f,Modernizr=new Modernizr,Modernizr.addTest("passiveeventlisteners",function(){var n=!1;try{var s=Object.defineProperty({},"passive",{get:function(){n=!0}});e.addEventListener("test",null,s)}catch(o){}return n});var l=n.documentElement,c="svg"===l.nodeName.toLowerCase();a(),t(i),delete f.addTest,delete f.addAsyncTest;for(var u=0;u<Modernizr._q.length;u++)Modernizr._q[u]();e.Modernizr=Modernizr}(window,document);
</script>

<div id="fixed-content" class="js-isolated-scroll fixed">
  <p class="p-in-fixed">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab accusamus aliquam, beatae blanditiis, cum dicta earum eligendi esse eum inventore iusto molestiae necessitatibus nesciunt praesentium quod ratione, similique sit voluptates.</p>
</div>

<p class="p-in-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab accusamus aliquam, beatae blanditiis, cum dicta earum eligendi esse eum inventore iusto molestiae necessitatibus nesciunt praesentium quod ratione, similique sit voluptates.</p>

Or, am I overcomplicating things unnecessarily, as this could potentially be achieved simply by using CSS?

Answer №1

Update1:

This solution utilizes CSS only for webkit browsers, specifically the ::-webkit-scrollbar property.

body{
  position: relative;
  background-color: #ccc !important;
  padding: 20px 20px 20px 50%;
}
.fixed {
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  padding: 20px;
  overflow: auto;
  position: fixed;
  border: 1px solid #333;
  width: calc(50% - 70px);
  background-color: #f8f8f8;
}

.fixed::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}
<div class="js-isolated-scroll fixed">
  <p class="p-in-fixed">Text goes here.</p>
</div>

<p class="p-in-body">More text here.</p>

A potential approach could involve toggling a class on the body or parent element when hovering over a scrollable div to prevent scrolling on the parent using CSS.

$('.js-isolated-scroll').bind('mouseenter mouseleave touchstart touchend', 
function() {
    $("body").toggleClass("no-scroll"); 
});
body{
  position: relative;
  background-color: #ccc !important;
  padding: 20px 20px 20px 50%;
}
.fixed {
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  padding: 20px;
  overflow: auto;
  position: fixed;
  border: 1px solid #333;
  width: calc(50% - 40px);
  background-color: #f8f8f8;
}

.no-scroll {
    overflow: hidden;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fixed-content" class="js-isolated-scroll fixed">
  <p class="p-in-fixed">Sample text.</p>
</div>

Answer №2

Check out this snippet. A unique approach I used is to separate the scroll functionality for better control.

In your scenario, the body contained the scroll, causing issues with the fixed div. By creating a container element for the paragraphs within the body that have scrolling capabilities and placing the fixed content outside of it, you can overcome this problem.

Here's the modified HTML structure:

<div id="container">
  <p class="p-in-body">...</p>
</div>

<div id="fixed-content" class="fixed">
    <p class="p-in-fixed">...</p>
</div>

With CSS adjustments made to html, body styles and the addition of #container:

html, body{
  padding: 0;
  width: 100%;
  height: 100%;
}
.fixed {
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  padding: 20px;
  overflow: auto;
  position: absolute;
  border: 1px solid #333;
  width: calc(50% - 40px);
  background-color: #f8f8f8;
}


#container{
  position: relative;
  background-color: #ccc !important;
  padding: 20px 20px 20px 50%;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

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

Tips for ensuring all buttons are evenly spaced from a surrounding div

Here’s the current setup - .box{ background-color: #e61a39; width: 25%; float:left; margin: 0px; text-align: center; min-height: 380px; } #container{ width: 90%; margin: auto; } <section id="container"> <div class="box"> <img src="http ...

The custom component I created seems to be unaffected by the inline styles in React

Having an issue with a custom component where I am trying to add margin-top in one of my uses. I attempted using <MyComponent style={{ marginTop: '10px' }}> and also const myStyle = { marginTop: '10px' }; `<MyComponent style= ...

Adjusting the width of the body container in a 2-column layout with menu padding is causing gaps to appear on the right side of

I'm having trouble getting my body div to fill the width of the page and align with the right side of my sidebar. Whenever I add padding to the sidebar, it creates blank space on the right that I can't seem to get rid of. Here is the code I am us ...

Unable to load the webpage

After the successful ajax request from the server, I want to display the div.valid_box with the data.message and proper CSS. This part works well, but after that, I just need it to load a new page called index.php, which is the admin panel, but it doesn&ap ...

Browsing a container with JavaScript

I am attempting to display one div at a time and scroll through them repeatedly. I found and modified a Fiddle that works as intended, but when I try to implement it on my own test page, the divs do not scroll as expected. Here is the Fiddle example: http ...

Having trouble downloading the Chip component in Material-UI? Learn how to fix the download issue

I used the UI to upload a file, and now I want to download it either after some time or instantly. I tried implementing this using the <Chip> component, but it's not working. I need assistance in resolving this issue. Uploaded File: const data ...

Error code 12030: AJAX request status

When making an ajax XMLHttpRequest using the POST method, I am encountering a readyState of 4 with a status of 12030. It is known that 12030 is a Microsoft-specific state code indicating that the connection was not sustained. However, I have been unable to ...

Unstyled Cards Failing to Receive Design

I am currently working on creating a prototype that utilizes two Bootstrap 4 cards to display information from a form and store related information from another form in the second card. The current layout of this setup can be observed below: This JSFiddle ...

Ways to address the issue of "$ is not a function"

Whenever I attempt to upload an image, this error message pops up: $ is not a function The source of the error can be found here: $(document).height(); ...

Best practices for displaying output in Python Flask after submitting an HTML form

Embarking on my first web development project, I delved into Flask. Recently, I created a basic temperature converter, running it on my local host. The webpage featured a form input for entering a value, two radio buttons for selecting Fahrenheit or Celsiu ...

What is the best way to implement setState in this scenario?

Receiving warnings in the console that say: Avoid changing state directly. Instead, use setState() method: react/no-direct-mutation-state When I tried changing this.state.turn = this.state.turn === 'X' ? 'O' : 'X'; to this.s ...

vertical alignment, almost there

Is there a way to align a block of text so that the top of the first line is positioned 50% down from the top of the td element? Imagine this scenario, where the top of the first row is exactly at the 50% mark. -------------- | | | ...

Using Express for Managing Subdomains, Redirects, and Hosting Static Files

I am struggling to configure Express in a specific way and can't seem to get it right. Despite researching on various platforms like SO, I still can't figure it out. Hopefully, by explaining my intentions here, someone can guide me in the right d ...

Ways to display an icon in Angular 10 only when it is hovered over

Just getting started with Angular and still learning the concepts. Trying to figure out how to show an icon only when it's hovered over. Can anyone assist me? Sorry, can't share the code because of company rules. The icons are for sorting and ...

Working with the collapse event in Bootstrap

After purchasing a template from ThemeForest, I found it to be absolutely amazing. However, I am struggling with using Bootstrap as it seems quite complex. The left menu is structured with collapsible ul and multiple li elements. I am seeking assistance o ...

Verify whether a document retrieved from mongoDB contains a certain property

Dealing with user accounts in Mongoose, I have set it up so that the user can use their phone number to sign in: const account = await db.Account.findOne({ phone: req.body.phone }) : Now, I need to confirm if there is a property named verified in the acco ...

Surprising pause in the menu transition animation

Currently, I am in the process of developing a menu that seems to have some flaws. One issue is that it appears a bit choppy, but the more concerning problem is the half-second delay after clicking an item before it animates. The concept behind this menu ...

How can I go about refreshing my mapbox gl source data?

Hey there, I'm encountering an issue when attempting to update my mapbox source on click. I currently have two sources (cells, heatmap), and I am trying to add a new source using this code snippet: this.map.addSource("points", { type: "geojson", ...

JSON isn't transmitting any information

Having an issue with Json that's puzzling me. I'm using ajax to call a Controller method that takes a string as input and returns a List of my defined class. The json call is triggered by a dropdown menu change, loading the corresponding fields ...

Modal containing react-select dropdown opens successfully

I am currently facing an issue with my custom modal that contains 2 react-select components. The modal body is set up to auto scroll when the content exceeds its size, but the problem arises when the dropdowns of the react-select components open within the ...