What is the relationship between html, body, and window when scrolling through code?

I've been working on adding a scroll-to-top button to my website. After doing some research online, I came across this code snippet:

$('html, body').animate({scrollTop:0}, 'slow');  

It's interesting that they are trying to scroll both the html and body elements. However, when I played around with the overflow: hidden property on the body tag, I realized that having a scrollbar for both html and body may not work as expected. Then I found an alternative method on MDN:

window.scroll({
  top: 0,
  left: 0,
  behavior: 'smooth'
});

It's worth mentioning that the window object is global and cannot be scrolled.

  1. Does the window.scroll function internally scroll the html element or the body element?
  2. Is it possible to scroll the body element at all? I experimented with using overflow: hidden on html and then overflow: scroll on body, but couldn't get a scrollbar to show up.

Answer №1

window.scroll() is used to effectively scroll the document.scrollingElement* which is now identified as the <html> element, although it was previously the <body> element in some UAs and still in Quirks mode.

The inclusion of document.scrollingElement is a recent update, so older code may still reference both <body> and <html> to accommodate different browsers.

*According to specifications, it actually scrolls the "viewport", but this essentially equates to the same thing since Step 12 of the scroll algorithm designates the " document’s root element as the associated element" for the actual scrolling operation.

const frameContent = `<html>
  <body><h1 style='height:300vh'>%s Mode</h1>
  <script>
    scroll(0, 200);
    parent.postMessage({
      compatMode: document.compatMode,
      html: document.documentElement.scrollTop,
      body: document.body.scrollTop,
    }, '*')
  <\/script>`;
document.querySelectorAll("iframe").forEach((el, i) => {
  el.src = `data:text/html,` + encodeURIComponent(
      (i ? "<!DOCTYPE html>" : "") + // set the first frame to Quirk mode
      frameContent.replace("%s", i ? "Default" : "Quirk")
    );
});
onmessage = ({data}) => console.log(data)
<iframe></iframe>
<iframe></iframe>

Answer №2

  1. Is the html element or body element scrolled by window.scroll?

Neither. It actually scrolls the viewport. For more details on how scrolling works, refer to the CSSOM view spec.

  1. Can we scroll the body element at all? I tried overflow: hidden on html and then overflow: visible on body but no scrollbar appeared.

Yes, it is possible to scroll the body element, however using overflow: visible will not show a scrollbar. You need to use either overflow: scroll or overflow: auto for that. Additionally, the content within the body must exceed its boundaries in order to enable scrolling as shown below:

html {
  overflow: scroll;
  width: 630px;
}  
body { 
  height: 80px;
  overflow: auto;
}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This setup shows two vertical scrollbars - one on the viewport due to overflow: scroll on the html element, and another on the body because of the overflowing content with overflow: auto set.

If both elements have overflowing content, both scrollbars can be made scrollable.

html  {
  overflow: auto;
  border: 2px solid red;
}  
body { 
  height: 110vh; /* exceeds the viewport - though notice:
                    from the red and blue borders, not the
                    html element. */
  overflow: auto;
  border: 2px solid blue;
}
p { 
  height: 130vh; /* exceeds the body element */
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<p>

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

Verify if an interval is currently active and vice versa

My web app has basic authentication implemented. When I log in, an interval is set up like this: $("#login").click(function(e) { var interval = setInterval(function(){myFunction();}, 2000); }); However, when I log out, the interval should stop: $("#lo ...

How come my footer is appearing at the top of my webpage?

I have encountered a problem where the footer is displaying on top of my page, despite not using any floats, wrappers, or grids in my code. The code snippet can be found below this text. Could someone assist me in identifying why this issue is occurring ...

Internet Explorer does not return results when using AJAX during the onchange event (specifically for IE only

My code is functioning correctly on other browsers, however in IE it does not provide any result when I select the dropdown button. Instead, it changes and displays an empty result. This is my AJAX: $("#book").change(function(){ var DOMBULK = $(" ...

Receive immediate updates of the text input in real-time using the onkeydown event handler in Javascript

I attempted to display the content of the input box in a message div simultaneously, however, the output always seems to be one step behind. function showWhatsWritten(){ var tempText; tempText = document.getElementById("text").value; document.getEle ...

An unexpected import token was encountered while using ReactJS and Babel

Every time I attempt to launch my application, an error message pops up that says: (function (exports, require, module, __filename, __dirname) { import { Row } from '../grid' SyntaxError: Unexpected token import I've experimented with vari ...

"By selecting the image, you can initiate the submission of the form

I am trying to figure out why clicking on the image in my form is triggering the form submission by default. Can someone please provide guidance on this issue? <form name="test1" action="er" method="post" onsubmit="return validateForm()" <input ty ...

Adjust the height of a div element back to its original size using jQuery after it

My goal was to create a dynamic div that expands when the user clicks on it, revealing more information. I have successfully achieved this functionality. However, my next objective is to modify the script so that the height of the div changes back when the ...

What is the process for forming a series of arrays from one singular array?

If I have a large array consisting of numbers from 1 to 18, is there a simple method to split it into pairs like [1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14] for n=2? The special case of n=2 is all I need. ...

AngularJS controller experiencing scope() function returning undefined issue

I've been working with a function inside the controller: $scope.passValues = function (param1){ return "foo"; }; console.log($scope.passValues()); It logs foo, but then I tried this: $scope.passValues = function (param1){ return param1; ...

Strategies for improving the efficiency of HTML and styles in a generated document

Generating the invoice printing form layout using dynamically created Razor views through RazorEngine can result in messy and hard-to-read code. The repetitive use of words like top, left, width, and height makes it challenging for human inspection and deb ...

Attempting to iterate through a Query each loop for the Raphael object

I'm currently facing a challenge with creating a jQuery .each() function to iterate through an array that I've constructed from a Raphael object. While I am able to achieve this using a traditional JavaScript for-loop: for (var i = 0; i < reg ...

What is preventing me from setting a background image in Angular 13?

Trying a different approach based on advice from Stack Overflow, I attempted the following: <div [style.background-image]="'url(https://picsum.photos/200)'"></div> Unfortunately, this resulted in no effect and the image was ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Implementing jQuery Validate along with Gritter Notification

I'm struggling with the jquery notification formReset() function along with "e.preventDefault();" and gritter notifications. In my code, I use the eventAdd() function in the submitHandler of a validator. Inside the eventAdd function, I trigger a gritt ...

Establishing the footer within dompdf

This snippet demonstrates the specified behavior (jsfiddle). <!--Footer--> <div id="footer"> <span class="alignleft">$unique_ID</span> <span class="alignright"> Page <span class="pagenum"></span></span> < ...

Steps to forward a restricted user to a specific webpage

I am currently utilizing NextJs and am in the process of creating a redirecting function for users who have been banned or blocked from accessing the DB/session. My attempt at this involved: redirect.js, where I created a custom redirect function. impo ...

`In the event that a series of criteria is unfulfilled in a JavaScript forEach() loop`

My IntersectionObserver utilizes a forEach method to invoke certain functions when a condition is met for each item in an array: const sections = document.querySelectorAll("section") function removeHighlight(id) { someElementArray[id].cl ...

Optimize Your Website for Various Screen Sizes

Can anyone assist with centering my webpage on small screen sizes? Everything looks good at the normal width of 989px, but once it shrinks, it shifts to the left and leaves excess white space on the right. I've tried various methods to correct this is ...

The array is giving back null values

When making a POST request with AJAX and sending data in JSON format, everything seems to be working fine until trying to print out a specific index value from the decoded array, which returns null. What could be causing this issue? Here's the AJAX re ...

What are the implications of incorporating listeners in redux action creators?

While developing my app, I have a feature that involves constantly monitoring location changes and updating the store accordingly. One question that has arisen is whether it would be beneficial to keep the listeners inside the action creator rather than th ...