Ways to stop the parent container from causing the child element set as fixed to scroll

When I have a parent and children with the property 'overflow:auto', scrolling the children causes the parent to start scrolling after it reaches the end. How can this be prevented?

I do not want the parent container to scroll even after the children's scroller ends.

Below is the CSS code for the children:

.children{
  height:20em;
  overflow:auto;
  border:2px solid green;
  position:fixed;
  left:0;
  background:gray;
  z-index:100;
}

I am experiencing this issue with displaying large content, so please click on the link below to visit the live demo and scroll the children (Gray backgrounded).

Live Demo

Answer №1

By default, the browser behaves in a certain way.

To prevent this behavior, you can refer to the following codepen created by Leland Kwong.

http://codepen.io/LelandKwong/pen/edAmn

   var trapScroll;

(function($){  

  trapScroll = function(opt){

    var trapElement;
    var scrollableDist;
    var trapClassName = 'trapScroll-enabled';
    var trapSelector = '.trapScroll';

    var trapWheel = function(e){

      if (!$('body').hasClass(trapClassName)) {

        return;

      } else {  

        var curScrollPos = trapElement.scrollTop();
        var wheelEvent = e.originalEvent;
        var dY = wheelEvent.deltaY;

        // only trap events once we've scrolled to the end
        // or beginning
        if ((dY>0 && curScrollPos >= scrollableDist) ||
            (dY<0 && curScrollPos <= 0)) {

          opt.onScrollEnd();
          return false;

        }

      }

    }

    $(document)
      .on('wheel', trapWheel)
      .on('mouseleave', trapSelector, function(){

        $('body').removeClass(trapClassName);

      })
      .on('mouseenter', trapSelector, function(){   

        trapElement = $(this);
        var containerHeight = trapElement.outerHeight();
        var contentHeight = trapElement[0].scrollHeight; // height of scrollable content
        scrollableDist = contentHeight - containerHeight;

        if (contentHeight>containerHeight)
          $('body').addClass(trapClassName); 

      });       
  } 

})($);

var preventedCount = 0;
var showEventPreventedMsg = function(){  
  $('#mousewheel-prevented').stop().animate({opacity: 1}, 'fast');
}
var hideEventPreventedMsg = function(){
  $('#mousewheel-prevented').stop().animate({opacity: 0}, 'fast');
}
var addPreventedCount = function(){
  $('#prevented-count').html('prevented <small>x</small>' + preventedCount++);
}

trapScroll({ onScrollEnd: addPreventedCount });
$('.trapScroll')
  .on('mouseenter', showEventPreventedMsg)
  .on('mouseleave', hideEventPreventedMsg);      
$('[id*="parent"]').scrollTop(100);

I trust that this information will be beneficial to your understanding! :)

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 successfully passing import as props arguments in React JS

I am using react-lotties and would like to add different animations to multiple divs by just changing the URL of the lotties As a beginner in React, please be kind :) This is my code snippet : My Lotties Component : import React, { Component } f ...

Tips for extracting Stripe response post payment using a client-side-only integration

My current component handles sending a payment order to my stripe account on the client-side. Everything seems to be working fine, but I'm struggling to find a way to retrieve the response or token from stripe containing the order details, which I nee ...

Aligning an element vertically with the surrounding text on the same line

Trying to incorporate inline input range elements in a way that aligns with the line while also aligning with the right edge of the outer div has proven to be challenging. The HTML on the site is formatted using prettify, resulting in <span> elements ...

What is the best way to showcase all menu and submenu items in separate dropdown lists?

Having trouble with my code, it's not functioning properly. I can't pinpoint the error. The menu displays correctly but the submenu isn't showing up under specific menus. Here is the code snippet: ##Table: menus## id name ...

Internet Explorer is unable to display tables at 100% height

Feel free to use this code snippet in an HTML file to display the output: <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style> html, body { margin:0; padding:0; ...

Hover over elements to reveal D3.js tool tips

Currently, I am utilizing a tutorial for graph tooltips and finding it to be very effective: http://bl.ocks.org/d3noob/c37cb8e630aaef7df30d It is working seamlessly for me! However, I have encountered a slight problem... In the tutorial, the graph disp ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

The index.html file is failing to load/render when using app.js

I am currently in the process of creating a to-do list using an older tutorial. The app.js file seems to be functioning properly, however, when I try to run it locally, all I see is a blank page instead of my HTML content. Here is the code found in the ap ...

Using Google Maps to trace a line showing the distance traveled

I want to create a 'distance traveled' polyline along a set route using V3 of the Google Maps API. The polyline should pass through multiple waypoints/legs. Currently, I am using the DirectionsService to draw the entire route. In addition, I a ...

Issue with Android Cordova: Unable to assign value to property 'text' because it is set to null

While attempting to run cordova prepare on my project, I encountered the following error : (node:11384) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'text' of null at updateProjectAccordingTo (C:\Users\Utilisateur&b ...

Enhancing nested return efficiency

Consider the following two JavaScript functions: function (){ return _.includes(someLongArray, value) && someSimpleValue; } VS function (){ return someSimpleValue && _.includes(someLongArray, value); } Which function will have bett ...

Navigating through nested nodes within an Angular directive can be achieved by

Here is some HTML code with a directive: <foo> <span>Bar</span> </foo> myapp.directive('foo', function () { return { restrict: 'E', replace: true, transclude: true, temp ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Is it possible to extract information from a website if the body or row does not contain any attributes?

As a beginner in the world of coding and this website, I kindly ask for some patience with me. I have successfully created code to scrape a particular website, extract data, and store it in a MySQL database. Everything is working smoothly. Now, my goal i ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

Configuring Angular to use ES6 syntax

Trying to integrate angular google maps with es6 syntax has been a challenge for me. In es5, the code typically looks like this: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key&ap ...

What is the best way to convert this JavaScript iteration function into jQuery?

I recently encountered an issue with my JavaScript function that returns a list of elements with the class ".youtube", loops through them, and calls another function. The JavaScript logic is flawless, but I wanted to convert it into jQuery for better reada ...

Puzzle: Ensuring all properties of JavaScript objects within an array are defined

Consider the vue.js object provided below: FormattedData: Object 1: Object approved: true 2: Object approved: undefined 3: Object approved: false 4: Object approved: true Seeking a more effective and concis ...

Is it achievable to use the Jquery :after selector?

I am facing an issue with a menu script in my HTML code that looks like this: <ul class="cbp-tm-submenu" style="left: 50px;"> <li><a href="#" class="cbp-tm-icon-screen">Sorrel desert</a></li> <li><a href="#" ...

Interactive tool for crafting dynamic web experiences

I am in the process of developing a straightforward hosting website for my projects. However, I have noticed that many software options feature a split view for editing code and previewing changes, such as Dreamweaver. I am on the lookout for a live edito ...