Photo by Milad Fakurian on Unsplash

JavaScript's Different Size Properties for DOM Elements

Learn about the dimensional data attached to each JavaScript-selected element.

2023-06-29T14:50-07:00

I wrote the following code that changes an element's CSS properties based on the user's scroll position. Normally the element is fixed to the bottom of the screen, but I didn't want it to overlap with the footer once the user scrolls to the bottom of the page.

The example uses different height properties for different elements. For the browser window I grab the innerHeight property. For the body height I take the scrollHeight property. And for the footer height I use the offsetHeight property.

Each one of these properties has subtle differences. Window.innerHeight doesn't take into account any content that overflows the browser window — it only measures the height of the viewport. To get the no-overflow height for other elements, including padding and borders, use Element.offsetHeight. To get the height of an element's scrollable content, use Element.scrollHeight.

There are also corresponding width properties:

stopFixedScrollAboveFooter();

function stopFixedScrollAboveFooter() {
  stopFixedScrollAboveFooterHelper();
  window.onscroll = stopFixedScrollAboveFooterHelper;
}

function stopFixedScrollAboveFooterHelper() {
  const {scrollY: scrollPos, innerHeight: screenHeight} = window,
    bodyHeight = document.body.scrollHeight,
    footerHeight = document.querySelector("footer").offsetHeight,
    isRemoveFixed = scrollPos + screenHeight > bodyHeight - footerHeight,
    fixedElem = document.querySelector(".fixed");
  fixedElem.style.position = isRemoveFixed ? "absolute" : "fixed";
  fixedElem.style.bottom = isRemoveFixed ? `${footerHeight}px` : 0;
}