0

As you can see here i have two sections which takes whole page. I want to detect while scrolling, if second section is visible by 20% and if so, then force it to smoothly scroll and lock that section so it takes whole space. And the same with other sections if add more.

(The smooth part i can do myself).

Anyone have idea how could i do something like that?

* {
    margin: 0;
    padding: 0;
}

#s1 {
  height: 100vh;
  background: red;
}

#s2 {
  height: 100vh;
  background: blue;
}
<section id="s1"></section>
<section id="s2"></section>
Malekai
  • 4,765
  • 5
  • 25
  • 60
Mike
  • 49
  • 5
  • 1
    Possible duplicate of [Can I detect the user viewable area on the browser?](https://stackoverflow.com/questions/9271747/can-i-detect-the-user-viewable-area-on-the-browser) – Russ J Mar 18 '19 at 14:23
  • I agree. Duplicate. And I don't think its possible with just pure html or css. – CmosBattery Mar 18 '19 at 14:27
  • 4
    Duplicate, and the user doesn't include any attempt to solve the problem... – Vinz243 Mar 18 '19 at 14:38

1 Answers1

0

var section = document.querySelector('section'),
    sectionHeight = section.offsetHeight,
    lastScrollTop = 0;
document.addEventListener("scroll", function() {
    var scrollY = window.pageYOffset || document.documentElement.scrollTop;

    if (scrollY > lastScrollTop) { //on scroll down
        if (scrollY >= sectionHeight * 0.2 && scrollY < sectionHeight) { //if 20% of section2 is visible
            window.scrollTo(0, sectionHeight * 1); //scroll to section2
        } else if (scrollY >= sectionHeight * 1.2 && scrollY < 2 * sectionHeight) { //if 20% of section3 is visible
            window.scrollTo(0, sectionHeight * 2); //scroll to section3
        } else if (scrollY >= sectionHeight * 2.2) { //if 20% of section4 is visible
            window.scrollTo(0, sectionHeight * 3); //scroll to section4
        }
    }
    lastScrollTop = scrollY <= 0 ? 0 : scrollY;
});
* {
    margin: 0;
    padding: 0;
}
html,body{
  scroll-behavior: smooth;
}
section{
  height: 100vh;
}
#s1 {
  background: red;
}
#s2 {
  background: blue;
}
#s3{
  background: yellow;
}
#s4{
  background:purple;
}
<section id="s1"></section>
<section id="s2"></section>
<section id="s3"></section>
<section id="s4"></section>
h3t1
  • 1,126
  • 2
  • 18
  • 29