0

Good day. Implemented smooth scrolling for javascript on the site. Everything works fine, the page itself scrolls strictly to the start of the desired section. But since I have a fixed header, but it takes up part of the review. The question is how to add the height of this header to the scroll bar

js

  const anchors = document.querySelectorAll('.scroll-href')

  anchors.forEach(item => {
    item.addEventListener('click', (e) => {
      e.preventDefault()

      const blockID = item.dataset.scroll

      document.getElementById(blockID).scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      })

    })
  })

hmtl

<header class="header">
 Some content
</header>

<a href="#" data-scroll="reviews-section">Scroll to reviews</a>
<a href="#" data-scroll="services-section">Scroll to services</a>
<a href="#" data-scroll="cases-section">Scroll to cases</a>
<a href="#" data-scroll="footer-section">Scroll to footer</a>

<section class="reviews" id="reviews-section">Some content</section>
<section class="services" id="services-section">Some content</section>
<section class="reviews" id="cases-section">Some content</section>
<section class="reviews" id="footer-section">Some content</section>

css

.header
  padding: 10px 0px
  position: fixed
  top: 0
  left: 0
  width: 100%
  background-color: #050505
  z-index: 10

Link to site https://mpleader.pro/ (Possible bugs on mobile devices)

Section view without scrolling Section view without scrolling

Section view with scrolling Section view with scrolling

Akaev Dzhalal
  • 129
  • 1
  • 7
  • Does this answer your question? [scrollIntoView Scrolls just too far](https://stackoverflow.com/questions/24665602/scrollintoview-scrolls-just-too-far) – Reyno Jan 11 '22 at 14:58

1 Answers1

1

set a scroll-margin-top for your sections

section{
 scroll-margin-top: 10px; /* normally that would be equal to your header's height */
}
Sherif Wael
  • 435
  • 2
  • 9