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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
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.