Consider I have a list of questions. When I click on the first question, it should automatically take me to the bottom of the page.
For a matter of fact, I do know
Late to the party, but here's some simple javascript-only code to scroll any element to the bottom:
function scrollToBottom(e) {
e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}
one liner to smooth scroll to the bottom
window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
To scroll up simply set top
to 0
Below should be the cross browser solution. It has been tested on Chrome, Firefox, Safari and IE11
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
window.scrollTo(0,document.body.scrollHeight); doesn't work on Firefox, at least for Firefox 37.0.2
Sometimes the page extends on scroll to buttom (for example in social networks), to scroll down to the end (ultimate buttom of the page) I use this script:
var scrollInterval = setInterval(function() {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);
And if you are in browser's javascript console, it might be useful to be able to stop the scrolling, so add:
var stopScroll = function() { clearInterval(scrollInterval); };
And then use stopScroll();
.
If you need to scroll to particular element, use:
var element = document.querySelector(".element-selector");
element.scrollIntoView();
Or universal script for autoscrolling to specific element (or stop page scrolling interval):
var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
var element = document.querySelector(".element-selector");
if (element) {
// element found
clearInterval(scrollInterval);
element.scrollIntoView();
} else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) {
// no element -> scrolling
notChangedStepsCount = 0;
document.documentElement.scrollTop = document.documentElement.scrollHeight;
} else if (notChangedStepsCount > 20) {
// no more space to scroll
clearInterval(scrollInterval);
} else {
// waiting for possible extension (autoload) of the page
notChangedStepsCount++;
}
}, 50);
A simple way if you want to scroll down specific element
Call this function whenever you want to scroll down.
function scrollDown() {
document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight
}
ul{
height: 100px;
width: 200px;
overflow-y: scroll;
border: 1px solid #000;
}
<ul id='scroll'>
<li>Top Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Bottom Here</li>
<li style="color: red">Bottom Here</li>
</ul>
<br />
<button onclick='scrollDown()'>Scroll Down</button>
Vanilla JS implementation:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView