Is there a way to assign the scroll event context to `document.body` instead of `window`?

Discovery

As I delved into the intricacies of web development, I stumbled upon a curious observation. In a particular MDN page, I noticed that the left and right sidebars had their scrollbars contained within themselves. However, the content block's scrollbar extended to the global context.

https://i.stack.imgur.com/FXJ7L.gif

Upon inspecting the DOM tree, I realized that neither the body nor the html tags had a defined height property. Consequently, there were no elements with fixed heights serving as scrollable containers between the content area and the topmost window object. An illustration of a scrollable container

Dilemma

This setup essentially made the window the overflow container for the content area. To verify this hypothesis, I added scroll event listeners to both the window and document.body. Surprisingly, only the window event was triggered.

window.addEventListener("scroll", (e) => console.log("window scrolling")) 

document.body.addEventListener("scroll", (e) => console.log("body scrolling"))

Discontent with this configuration, I desired the scroll context to be document.body instead of window, thereby ensuring that the scroll event originated from the body tag rather than the window.

Attempts

In an attempt to rectify the situation, I assigned a height property to the body tag.

height: 100vh

Subsequently, I reattached the scroll event listener to it. Unfortunately, the event failed to trigger, leaving me perplexed about the underlying cause.

The conventional wisdom dictates that adding a height property to a parent element with a value lower than its children should render it scrollable. So, where did my logic falter?

I might be overlooking some fundamental aspect, but I remain clueless. Your guidance on this issue would be immensely appreciated. Thank you!

References:

Answer №1

When setting the overflow property for both the <body> and the <html> elements, avoid using visible due to the effects of Overflow Viewport Propagation.

To ensure a scrollbar appears, the height of the <body> must be smaller than its content:

window.addEventListener("scroll", () => console.log("window scrolled"));
document.body.addEventListener("scroll", () => console.log("body scrolled"));
html {overflow-y: hidden}
body {
  margin: 0;
  height: 100dvh;
  overflow-y: scroll;
}
main {
  height: 200%;
  background-color: red;
}
<body>
  <main></main>
</body>

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

How to use Nokogiri to efficiently extract targeted nodes from HTML

In my Ruby script, I am trying to extract specific values from an HTML document using the Nokogiri gem. The HTML content I'm parsing includes information about a user and their registered device. #!/usr/bin/ruby require 'Nokogiri' doc = No ...

Tips for executing a script while updating npm version

Can a script be executed during the npm version command, after the release number has been incremented but before the git tag is created and pushed? ...

Is there a way to eliminate unknown white gaps in the content?

I have encountered a very perplexing issue. When accessing this site on Safari, an additional 4-500px of scrollable whitespace is added. This is clearly not the intended behavior, but I am struggling to understand what is causing this space :S Upon inspe ...

Getting the x-axis points on Google charts to start at the far left point

I have integrated the Google API for charts into my application and am using multiple charts on the same page. However, I am facing an issue with setting padding for the charts. When I include more data points, the chart area occupies more space in the div ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Transferring information through AJAX to the current page using a foreach loop in Laravel 5

As a newcomer to ajax and laravel 5, I am eager to learn how to pass data with ajax to populate a foreach loop in laravel 5 on the same page. <div class="row" style="margin:3% 0px 0px 0px"> @foreach($warung_has_kategoriwarungs['i want pass ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

Enhance Your Images: Creating Stunning Colored Overlay Effects using HTML and CSS

I'm currently working on implementing an overlay effect for images on a webpage. The idea is that when the cursor hovers over an image, it will change color slightly. However, I'm facing some issues and the desired effect is not reflecting. How c ...

Regular Expression for jQuery to match both letters and numbers, including special characters

Is there a way to validate text input using a jquery regex that includes specific characters such as A-Z, a-z, 0-9, !, #, $, £ (preferably all currency characters), %, &, -, and _? If so, how can this be implemented? I have attempted to use the regex pa ...

Discover the secrets of extracting the ID from a MenuItem within a Menu

Table Ui with menu Struggling with fetching the correct user ID in the edit button The edit button for all users is only displaying the last user's ID If the edit button is not nested inside the Menu, it works fine. However, within the Menu, it onl ...

What is the best method for transforming a stream into a file with AngularJS?

Currently, I have a server returning a file stream (StreamingOutput). My goal is to convert this file stream into an actual file using AngularJS, javascript, JQuery, or any other relevant libraries. I am looking to display the file in a <div> or ano ...

How can I duplicate or extract all the formatting applied to a specific text selection in Ckeditor?

I am currently utilizing CKEditor version 3.6 within my Asp.net MVC 3 Application. One of my tasks involves creating a Paint format option similar to Google Docs. I am looking to integrate this feature into CKEditor. Is there a way in CKEditor to transfe ...

Encountering an undefined response in API call using Fetch with Express Nuxt

I've hit a roadblock with a task involving Express, API, and Fetch. I'm utilizing Nuxt along with Shopify API endpoints to retrieve data such as orders. Below is my express API Endpoint which should return an array of objects (orders). const bod ...

Promise disregards the window being open

I'm facing an issue with redirecting users to Twitter using window.open in a specific function. It seems like the instruction is being ignored, even though it works perfectly on other pages. Any ideas on how to fix this? answerQuestion() { if ...

Ways to verify that window.open is being invoked from a React component

In my React component, I have a set of nested components, each with its own checkbox. The state hook rulesToDownload starts as an empty array and dynamically adds or removes IDs based on checkbox selection. Upon clicking the 'download' button, t ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...

Issues with inconsistent behavior of the select option in a form

Having some trouble with my form code. When I checked the web page, there seems to be an extra element that shouldn't be there. You can view the webpage . Inspecting it in browser developer mode, I found this extra element . Can you please help me ide ...

Access JSON file without considering any custom comments

Is there a way to extract the JSON data from 'file.json' without including any comments? # Comment01 # Comment02 { "name": "MyName" } I have tried using this code snippet: var fs = require('fs'); var obj; fs.readFile('./file. ...