Home > Back-end >  How to scroll to a certain point and then come back on top using the scroll function in javascript?
How to scroll to a certain point and then come back on top using the scroll function in javascript?

Time:12-22

I have a website where after a certain Y point of scroll it has to scroll down all of the sudden to another point under the previous one. The problem is, using the code that I have now, I can't turn back up again, because it create a loop where "window.scrollY" doesn't change and the function keep bringing me down.

window.addEventListener("scroll",scroll1);
function scroll1() {
    if (window.scrollY > 350) {
        window.scrollBy(0, 250);
    } 
}

CodePudding user response:

What you're describing is 'scroll-jacking' and isn't usually a good thing to do- however what you want is EASY to do. You could simply remove the event listener after scrolling. With your example:

  window.addEventListener("scroll",scroll1);
   
    function scroll1(){
        if (window.scrollY > 350) {
            window.scrollBy(0, 250);
            window.removeEventListener("scroll",scroll1)
        } 
    } 

This will let you scroll past what you want just the one time. If you wanted to have this happen every single time you scrolled back up- you could set a boolean as a flag.

  const setScroll = (window) => {
    let shouldSkip = true;
    window.addEventListener("scroll", scrollFunc);
    function scrollFunc(e) {
      // if we're at the top of the page, set shouldSkip to true
      // so that we will scroll past the 400 mark.
      if (window.scrollY == 0) shouldSkip = true;
      if (window.scrollY > 400 && shouldSkip) {
        window.scrollBy(0, 250);
        // set shouldSkip to false, so that we can scroll back up
        shouldSkip = false;
      }
    }
  };
  // call our scroll controller on the window object
  setScroll(window);

Either way I would suggest not doing this to the entire window- it isn't accessible but that is definitely one way to do it.

Here is an example of how it works using the second code block. We skip past the orange DIV entirely on our way down, and it works again as long as we fully scroll up. example from second code block

  • Related