d
Amit DhamuSoftware Engineer
 

Scroll Into View With Offset

1 minute read 00000 views

Javascript has a native scrollIntoView API which can be be used like below.

const scrollIntoView = selector => {
  const element = document.querySelector(selector)

  if (element) {
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    })
  }
}

It doesn't have a way of providing an offset though which means the top of the element gets scrolled to the top of the viewport.

We can use window.scrollTo to create a scrollIntoViewWithOffset function which gives us that capability.

const scrollIntoViewWithOffset = (selector, offset) => {
  window.scrollTo({
    behavior: 'smooth',
    top:
      document.querySelector(selector).getBoundingClientRect().top -
      document.body.getBoundingClientRect().top -
      offset,
  })
}