← Back

Scroll Top class astro

Highlighting the current header link in Astro

The code you posted adds a class named ‘hide’ to the header when the user scrolls down and removes it when the user scrolls up. This class presumably sets the display of the header to none, effectively hiding it.

const header = document.querySelector('header')
let lastScrollTop = 0
window.addEventListener('scroll', () => {
  let scrollTop = window.scrollY || document.documentElement.scrollTop
  if (scrollTop > lastScrollTop) {
    header.classList.add('hide')
  } else {
    header.classList.remove('hide')
  }
  lastScrollTop = scrollTop
})

Here’s how it works:

It first selects the header element using document.querySelector(‘header’) and assigns it to the header variable.

It initializes a variable lastScrollTop to 0. This variable keeps track of the last known scroll position.

It adds a scroll event listener to the window. Inside the event handler, it calculates the current scroll position.

It compares the current scroll position with lastScrollTop. If the current scroll position is greater (i.e., the user has scrolled down), it adds the ‘hide’ class to the header. If the current scroll position is less (i.e., the user has scrolled up), it removes the ‘hide’ class from the header. Finally, it updates lastScrollTop with the current scroll position for future comparisons.

This approach should work across all modern browsers, including Safari.

However, if you’re experiencing issues with Safari’s overscroll behavior, you might need to adjust the CSS properties of the body or the specific element that’s causing the issue. For instance, you could try setting overscroll-behavior: none; on the body or the problematic element to prevent the browser from continuing to scroll beyond the boundary of that element 4.

the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never