0

I have set a scroll event listener on the document body to transform 100vh either up or down. This seems to work great on the first scroll down of 100vh and i can scroll back up 100vh to the start point as well. It doesn't seem to work though if i want to scroll down more than once. My markup is wrong some where but being fairly new to javascript i am struggling to see where i have gone wrong.

document.addEventListener('scroll', function() {
  var previousScrollPos = 0;
  var currentScrollPos = window.pageYOffset;
  var nextScrollPos = 0;
  if (currentScrollPos > previousScrollPos) {
    nextScrollPos = nextScrollPos - 100;
    document.body.style.transform = "translateY(" + nextScrollPos + "vh)";
  } else {
    nextScrollPos = nextScrollPos + 100;
    document.body.style.transform = "translateY(" + previousScrollPos + "vh)";
  }
});
body {
  width: 100%;
  height: 100%;
  transition: all 1s;
  color: black;
}

.section {
  height: 100vh;
  text-align: center;
  line-height: 100vh;
}

.section1 {
  background-color: white;
}

.section2 {
  background-color: green;
}

.section3 {
  background-color: red;
}

.section4 {
  background-color: yellow;
}
<div class="section section1">1</div>
<div class="section section2">2</div>
<div class="section section3">3</div>
<div class="section section4">4</div>
rufus
  • 717
  • 1
  • 9
  • 21
  • Are you trying to hijack the scroll event and make the user scroll up or down exactly 100vh? – BrunoFenzl Feb 23 '19 at 22:54
  • @BrunoFenzl I am yes, i'm just playing around with some transitions for a little project i'm working on – rufus Feb 23 '19 at 22:56
  • This behaviour is a little more involved than one may think. You have to disable the scroll and move the body/container yourself. The problem is that you cannot simply prevent the scroll event. Take a look in this answer for how to "prevent"scrolling. https://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily – BrunoFenzl Feb 23 '19 at 23:00

0 Answers0