GUIDE: Smooth Scrolling

❯❯ Using scrollIntoView()

The scrollIntoView method is a useful method we can use on DOM element nodes, for the page to align with the location of the element in question in the page. scrollIntoView() accepts an object literal with the properties behavior and block.

Scroll view into div, such that the div top edge is aligned with top edge of view
click to copy code segment
window.onload = function() {
  const box = document.querySelector(".box");
  box.scrollIntoView({ behavior: "smooth", block: "start" });
};

                              


If we wish to align the page view such that the lower edge of the element aligns with the lower edge of the page view, we set block: "end".
For an abrupt jump, do not include the behavior property, only the block.

❯❯ Using window.scrollTo()

window.scrollTo() is a bit more cumbersome, since instead of the block property, we need to specifically assign a top property that tells the page view, what top offset to take for the scroll. For this it is comfortable to calculate the total height to offset using getBoundingClientRect().

Scrolling using window.scrollTo() with getBoundingClientRect()
click to copy code segment
/* Assuming we have two divs, div1 is height 550px and div2 is 700px */
/* We want to scroll smoothly to div2 */
window.onload = function() {
  const div1 = document.querySelector(".box1");
  const div1Sizes = div1.getBoundingClientRect();
  window.scrollTo({ top: div1Sizes.bottom, behavior: "smooth" });
};

                              


Observe that for the top offset value we chose the bottom property (which describes position of the element's bottom edge to the bottom edge of the page), rather than height, since height doesn't take into account the bottom margin of the skipped element.

profile picture

WHO AM I?

Teacher
Thinker
Tinkerer