0

I'm trying to write a function that smooth scrolls up & down between sections of my website.

I found one answer on here which worked absolutely perfectly

Unfortunately, I am really struggling to add more than just two "elements".

I attempted to insert an "else if" statement, but that just broke the code.

Right now, it's safe to say, I have no idea how to solve this issue.

var firstsec = document.getElementById('one');
var secondsec = document.getElementById('two');
var lastScrollTop = 0;
window.onscroll = function(){
   var st = window.scrollY || document.documentElement.scrollTop; 
   if (st > lastScrollTop){
      secondsec.scrollIntoView({behavior: "smooth"});
   } else {
      firstsec.scrollIntoView({behavior: "smooth"});
   }
   lastScrollTop = st <= 0 ? 0 : st; 
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: sans-serif;
}

.container {
    height: 100vh;
}

section {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
}

#one {
    background: rgb(36, 164, 138);
}

#two {
        background: rgb(211, 79, 79);
}

#three {
        background: rgb(67, 91, 175);
}

#four {
        background: lightsalmon;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
   
</head>
<body>
    <div class="container">
        <section id="one">
            <h1>First Page</h1>
        </section>
        <section id="two">
            <h1>Second Page</h1>
        </section>
        <section id="three">
            <h1>Third Page</h1>
        </section>
        <section id="four">
            <h1>Fourth Page</h1>
        </section>
    </div>
</body>
</html>
JayRock
  • 1
  • 1

0 Answers0