JavaScript Window Sizes and Scrolling

For finding the width and height of the browser window, for scrolling the page using JavaScript, and more actions, the root document element document.documentElement is used. It corresponds to the <html> tag.

But, there are other essential methods and peculiarities we are going to cover in this chapter.

Width/height of the Window

For getting the window height and width, you can use clientWidth/clientHeight of document.documentElement , like this:

console.log(document.documentElement.clientWidth);

Please, also note that DOCTYPE plays a crucial role. For example, top-level geometry properties can work differently when there exists no <!DOCTYPE HTML> in HTML. But, in modern HTML, it is always required to write DOCTYPE.

Width/height of the Document

The core document element is document.documentElement involving the overall content. Hence, the document full size can be measured as document.documentElement.scrollWidth/scrollHeight. But, on the element for the whole page, properties like this don’t work properly. In Chrome, Safari, Opera no scroll exists, documentElement.scrollHeight can be less than documentElement.clientHeight . At first sight, it can sound weird. But, let’s see an example:

let scrollHeight = Math.max(
  document.body.scrollHeight, document.documentElement.scrollHeight,
  document.body.clientHeight, document.documentElement.clientHeight,
  document.body.offsetHeight, document.documentElement.offsetHeight
);
console.log('Full height of the document, with scroll out part: ' + scrollHeight);

Getting the Current Scroll

For DOM elements, there is a current scroll state in elem.scrollLeft/scrollTop.

In the majority of the browsers document.documentElement.scrollLeft/Top operates, where it is necessary to use document.body rather than document.documentElement.

But, these peculiarities are not a must to remember, as the scroll is available in the specific properties window.pageXOffset/pageYOffset, like here:

console.log('Current scroll on top: ' + window.pageYOffset);
console.log('Current scroll on left: ' + window.pageXOffset);

However, the properties above are read-only.

Scrolling: scrollTo, scrollBy, scrollIntoView

DOM must be fully built for scrolling the page from JavaScript.

You can scroll regular elements by changing scrollTop/scrollLeft. The same can be done by applying document.documentElement.scrollTop/Left. Also, there is an alternative solution such as specific methods window.scrollTo(pageX,pageY) and window.scrollBy(x,y).

The scrollBy(x,y) method can scroll the page relative to its current position. The button below shows it:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style>
      #smallDiv {
      height:100px;
      background-color: blue;
      }
      #bigDiv{
      height:1000px; 
      background-color: green
      }
    </style>
  </head>
  <body>
    <div id="smallDiv">
      <button id= 'btn'>Scroll the document vertically by 100 pixels</button>
    </div>
    <div id="bigDiv"></div>
    <script>        
      btn.addEventListener('click', () =>  window.scrollBy (0,100));
    </script>
  </body>
</html>

The scrollTo(pageX,pageY) method can scroll the page to absolute coordinates, in the way that the top-left corner of the visible part includes the (pageX, pageY) coordinates near the top-left corner of the document. It is similar to setting scrollLeft/scrollTop .

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style>
      #divId {
      height: 1200px;
      background: green;
      }
    </style>
  </head>
  <body>
    <div id='divId'>
      <button id='elem'>Click to scroll</button>
    </div>
    <script>
      const btn = document.getElementById('elem');
      btn.addEventListener('click', () => window.scrollTo({
        top: 500,
        behavior: 'smooth',
      }));
    </script>
  </body>
</html>

For scrolling to the very beginning scrollTo(0,0) can be used.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style> 
      #smallDiv {
      height:300px;
      background-color: blue;
      }
      #bigDiv{
      height:1000px; 
      background-color: green
      }
    </style>
  </head>
  <body>
    <div id="bigDiv">
      <button id='topBtn'>Click to scroll</button>
    </div>
    <div id="smallDiv">
      <button id= 'bottomBtn'>Scroll to top</button>
    </div>
    <script>      
      topBtn.addEventListener('click', () => window.scrollTo({
             top: 1000,
             behavior: 'smooth',
           }));
      bottomBtn.addEventListener('click', () => window.scrollTo(0, 0));         
    </script>
  </body>
</html>

The methods above work in the same way for all the browsers.

ScrollIntoView

There is another method - elem.scrollIntoView(top), as well. Calling elem.scrollIntoView(top) scrolls the page for making elem visible. In the case of top=true the document, the page will be scrolled for making elem appear on top of the window. The element’s upper edge will be aligned with the window top. In the case of top=false, the page scrolls for making elem appear at the bottom. The element’s bottom edge is aligned with the window bottom. The button, demonstrated below will scroll the page for making itself to show at the window top and the next button scrolls the page for showing it at the bottom:

<!DOCTYPE html> 
<html>
  <head>
    <style>
      h1{
      color: white
      }
      #content { 
      height: 700px; 
      width: 350px; 
      overflow: auto; 
      background: green; 
      }		
      #elem1 { 
      margin: 500px; 
      height: 300px; 
      width: 1000px; 
      background-color: white; 
      }
      #elem2 { 
      margin: 500px; 
      height: 400px; 
      width: 1000px; 
      background-color: red; 
      }			
    </style>
  </head>
  <body>
    <div>
      <button id = "btn1" onclick="scrollFunc1()">Scroll 1</button> 
      <br> 
      <button   id = "btn2"  onclick="scrollFunc2()">Scroll 2</button> 
      <br> 
      <button  id = "btn3" onclick="scrollFunc3()">Scroll 3</button> 
      <br> 
      <br> 
      <div id="content">
        <div id="start">
          <h1>
          Click on the scroll button</h2> 
        </div>
        <div id="elem1">
          <h2>Content 1</h2>
        </div>
        <div id="elem2">
          <h2>Content 2</h2>
        </div>
      </div>
    </div>
    <script> 
      function scrollFunc1() { 
      	var btn1 = document.getElementById("elem1"); 
      	btn1.scrollIntoView(false); // Makes the element 
      } 
      function scrollFunc2() { 
      	var btn2 = document.getElementById("elem2"); 
      	btn2.scrollIntoView(true); 
      } 
      function scrollFunc3() { 
      	var btn3 = document.getElementById("start"); 
      	btn3.scrollIntoView({block:'start'}); 
      } 
    </script>  
  </body>
</html>

Forbidding Scrolling

Sometimes it is necessary not to scroll the document. In other words, to make it unscrollable.

To meet that goal, you can set document.body.style.overflow = "hidden". As a result, the page will be frozen on the current scroll.

Here is how to do it:

<!DOCTYPE html>
<head>
  <style>
    div{
    width:300px;
    height:1000px;
    background-color: lightgreen;
    }
  </style>
</head>
<body>
  <select onchange="ChangeScrollState (this);">
    <option value="">show</option>
    <option value="hidden">hide</option>
  </select>
  <div>
    Select scroll hide or show 
  </div>
  <script>
    function ChangeScrollState (select) {
        document.documentElement.style.overflow = select.value;
    }
  </script>
</body>
</html>

So, with the first button above, you can freeze the scroll. With the second one, you can resume it.

The disadvantage of this method is that the scrollbar disappears. In case it occupies some space, then it is free, the content will jump to fill it.




Do you find this helpful?

Related articles