scroll to top
by momenelkamri
HTML
<p>Click the buttons to scroll to the top or to the bottom of the element with id="content".</p>
<a href="#top" onclick="scrollToTop()">Scroll to the top of the element</a>
<a href="#bottom" onclick="scrollToBottom()">Scroll to the bottom of the element</a>
<div id="myDIV">
<div id="content">
<div id="top" style="position:absolute;top:0;">Some text at the top</div>
<div id="bottom" style="position:absolute;bottom:0">Some text at the bottom</div>
</div>
</div>
CSS
#myDIV {
height: 250px;
width: 250px;
overflow: auto;
background: green;
}
#content {
margin:500px;
height: 800px;
width: 2000px;
background-color: coral;
position: relative;
}
JavaScript
//var elmnt = document.getElementById("top");
var links = document.getElementsByTagName('a');
var paddingTop = 100; //'height of your fixed header';
for(var i = 0, len = links.length; i < len; i++) {
links[i].addEventListener("click", function(e){
e.preventDefault();
var elmnt = document.getElementById(this.hash.substr(1));
scrollToTop(elmnt);
});
}
function scrollToTop(elmnt) {
elmnt.scrollIntoView(true); // Top
// now account for fixed header
var scrolledY = document.getElementById('myDIV').scrollTop; // window.scrollY;
var scrolledX = document.getElementById('myDIV').scrollLeft; // window.scrollY;
var srollYwithPadding = scrolledY - paddingTop
alert(scrolledY);
alert(srollYwithPadding);
alert(document.getElementById('myDIV').scroll);
if(scrolledY){
document.getElementById('myDIV').scroll(scrolledX, srollYwithPadding);
}
}
function scrollToBottom(elmnt) {
elmnt.scrollIntoView(false); // Bottom
}