ScrollSpy Video Tutorial


In this tutorial we will see how to listen to the scroll of a page to activate the corresponding menu item. This is an essential technique that is widely used on "one page" sites but also to create dynamic summaries.

Operation

In order to identify the elements to be observed we will use an attribute data-spy. Each element will also have a id which will be used by the menu links.


Section 1
Section 2
Section 3
Section 4

Then we will use the IntersectionObserver to find what section is visible on the screen. To simplify the detection of the element we will seek to get the intersection with a 1px bar located at 40% height (playing on the rootMargin).

const y = Math.round (window.innerHeight * ratio)
const observe = new IntersectionObserver (callback, {
  rootMargin: `- $ {window.innerHeight - y - 1} px 0px - $ {y} px 0px`
})

In the callback we will activate the visible element on the screen

const callback = function (entries) {
  entries.forEach (function (entry) {
    if (entry.isIntersecting) {
      activate (entry.target)
    }
  })
}

const activate = function (elem) {
  const id = elem.getAttribute ('id')
  const anchor = document.querySelector (`a (href =" # $ {id} ")`)
  if (anchor === null) {
    return null
  }
  anchor.parentElement
    .querySelectorAll (. 'active')
    .forEach (node ​​=> node.classList.remove ('active'))
  anchor.classList.add ( 'active')
}

We will adapt the function activate depending on the situation.