Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there alternatives to jQuery scrollTop?

Are there any alternatives that can be used in a function to scroll a browser to the top of the page? Right now I'm using: $('html, body').animate({scrollTop: '0px'}, 300);.

Is there maybe something else, or something that is not jQuery?

like image 693
d-_-b Avatar asked May 19 '12 02:05

d-_-b


People also ask

What is jQuery scrollTop?

jQuery scrollTop() Method The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.

What is $( window scrollTop ()?

scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .


1 Answers

Below is a pure JavaScript implementation of a scrollTop function. It uses setInterval as an asynchronous while loop that periodically decrements the pageYOffset value, which represents the scrollbar position relative to the top of the page.

To clarify, a while loop would block other scripts on the page from running and would make the scroll to the top appear instant, irregardless of the step value. Whereas, a setInterval with a 50ms iteration would only block the page once every 50ms and would update the scrollbar UI after each individual iteration.

The function takes a single parameter "step", which determines the rate that the scrollbar moves to the top of the screen. The smaller the step, the slower the rate in which the scrollbar moves to the top.

function scrollTop(step) {
    var start = window.pageYOffset;
    var count = 0;
    var intervalRef = setInterval( (function(interval, curOffset) {
        return function() {
            curOffset -= (interval * step);
            console.info("offset = " + curOffset);
            window.scrollTo(0, curOffset);
            console.info("pageYoffset = " + window.pageYOffset);
            count++;
            if(count > 150 || curOffset < 0) clearInterval(intervalRef);
        }
    })(step, start--), 50);
}

// scroll to the top from the middle of the page in about 5 seconds.
scrollTop(5);

// scroll to the top in about 1 second
scrollTop(15);

// scrolls to the top very fast!
scrollTop(35);

The interval is halted when the offset reaches 0, which means the scrollbar has reached the top of the page.

However, the count checker is there to limit the action to just 150 iterations to prevent you from locking up your browser, in case you decide to modify it. Otherwise, you can remove that condition.

like image 65
jmort253 Avatar answered Oct 02 '22 14:10

jmort253