<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<style>
.largeBlock{ min-width: 300px; height:300px; border: 1px solid red;}
</style>
</head>
<body>
<h1>Smooth Scroll without jQuery!</h1>
<div id="anchor-toc">
<h2>Table of content (toc)</h2>
<ul>
<li><a href="#anchor-2" onclick="smoothScroll('anchor-2');">smooth scroll to Anchor 2<a/></li>
<li><a href="#chapter-4" onclick="smoothScroll('chapter-4');">smooth scroll to Chapter 4<a/></li>
</ul>
</div>
<h2 id="target-1">Chapter 1</h2>
<div class="largeBlock"> some text</div>
<h2 id="anchor-2">Anchor 2</h2>
<a href="#anchor-toc" onclick="smoothScroll('anchor-toc');">scroll smooth to toc<a/>
<div class="largeBlock">This is the textblock below anchor 2</div>
<h2>Chapter 3</h2>
<div class="largeBlock"> some content </div>
<h2 id="chapter-4">Chapter 4</h2>
<a href="#anchor-toc" onclick="smoothScroll('anchor-toc');">scroll smooth to toc<a/>
<div class="largeBlock"> This is the text of chapter 4</div>
<h2>Chapter 5</h2>
<div class="largeBlock"> some content </div>
<h2>Chapter 6</h2>
<div class="largeBlock"> some content </div>
<a href="#anchor-toc" onclick="smoothScroll('anchor-toc');">scroll smooth to toc<a/>
</body>
</html>
// Code goes here
// based on
// http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
// use href="#anchorID" in your hyperlinks
// with smoothScroll('destinationAnchorID');return false; as the onclick event.
// <a href="#anchor-1" onclick="smoothScroll('anchor-1-id');">smooth scroll to Anchor 1<a/>
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
function smoothScroll(eID) {
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
return false;
}
/* Styles go here */