Hesham El Masry
Hesham El Masry

Reputation: 423

windows.scrollBy adding a fixed scrolling value to top

I have this function I'm using it in my AngularJS directive. This function scrolls to the top of the page, but this is not what I am aiming to do: I want to make it scroll up just 400px or 30%.

function scrollToTop() {
    var scrollDuration = 500;
    var scrollStep = -window.scrollY / (scrollDuration / 15);
    console.log(scrollStep);

    var scrollInterval = setInterval(function () {
        if (window.scrollY != 0) {
           window.scrollBy(0, scrollStep);
        } else {
           clearInterval(scrollInterval);
        }
    }, 15);
}

I tried changing the scrollStep variable to be 300 or any other number but I can't understand it actually.

Upvotes: 0

Views: 114

Answers (1)

Freeman Lambda
Freeman Lambda

Reputation: 3675

The total distanceToScroll is either an arbitrary number of pixels (i.e 400) or the whole window-scroll distance if it is less than 400. For that you can use Math.min. scrollStep is calculated dependently from distanceToScroll. You need to keep a count of "how much I've scrolled so far" in the setInterval, lets call it distanceScrolled. Keep scrolling until you have covered the distanceToScroll.

function scrollToTop() {
    var scrollDuration = 500;
    var stepDuration = 15;
    
    var distanceToScroll = Math.min(400, window.scrollY);
    
    var scrollStep = distanceToScroll / (scrollDuration / stepDuration);
    console.log(scrollStep);

    var distanceScrolled = 0;

    var scrollInterval = setInterval(function () {
        if (distanceScrolled < distanceToScroll) {
           window.scrollBy(0, -1 * scrollStep);
           distanceScrolled += scrollStep
        } else {
           clearInterval(scrollInterval);
        }
    }, stepDuration);
}

document.getElementById('btn').addEventListener('click', scrollToTop);
#very-high {
  height: 3000px;
}

#btn {
  position: fixed;
  right: 10px;
  top: 10px;
}
<div id="very-high"></div>
<button id="btn">Scroll</button>

Upvotes: 1

Related Questions