Scroll go straight to the next session of the page - vanilla JS

Asked

Viewed 65 times

1

I have some sections on the site, I would like when capturing the scroll, the site went straight to the next/previous sectio. As the sections are 100vh, I take the height dimension of the device screen and each scroll I move or drop this value (according to the direction of the scroll)

I have navigation buttons that go to the sections directly, are in the code as "dot".

const body = document.querySelector('.pf')
const viewHeight = Math.max(document.body.clientHeight, 
window.innerHeight || 0) //validado
const dot = document.querySelectorAll('.dot')
var lastScrollTop = 0

Array.prototype.forEach.call(dot, btn => {
    btn.addEventListener('click', () => {
        lastScrollTop = window.pageYOffset || 
        document.documentElement.scrollTop
    })
})

window.addEventListener(
    'scroll',
     e => {
         var scrollTop = window.pageYOffset || 
         document.documentElement.scrollTop
         if (scrollTop > lastScrollTop) {
             lastScrollTop = lastScrollTop + viewHeight
         } else {
             lastScrollTop = lastScrollTop - viewHeight
         }
         window.scrollTo(0, lastScrollTop)
     }
)

This code makes my page go up and down, always returning to the top (page height 0), not stopping in the sections as it should.

Wanted to make this effect without using libraries, only pure JS.

What is missing/ is wrong?

  • The problem is in click or scroll?

  • the problem is in scroll

  • Just to clarify a little bit: when you open the page you are in the first session, okay? When making a small scroll down you want to go to the second Section and so on? And when climbing the scroll go to the previous Section tb?

  • Exactly what I would like

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.