Smooth Scrolling using JQuery

So far, this is the best(for me) smooth scrolling "piece of code" using JQuery. It will use ID as the destination.
Here's the code for demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Smooth Scroll to Top</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript"> 
function ScrollTo(id, duration) 
{ 
      if(!duration) duration = 400; 
      var offset = $('#' + id).offset().top; 
      $('html,body').animate({scrollTop: offset}, duration); 
} 
</script>
</head>

<body>
<center>
<p id="destination" style="font-weight:bold; color:red;">THE DESTINATION</p>
<p>SCROLL DOWN</p>
<p>TO POPULATE BODY</p><p>TO POPULATE BODY</p><p>TO POPULATE BODY</p><p>TO POPULATE BODY</p><p>CLICK THE RED TEXT BELOW</p>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<a href="javascript:void(0)" onclick="ScrollTo('destination', 500)" style="font-weight:bold; color:red; text-decoration:none" title="Scroll to Top">I'M GOING TO THE DESTINATION</a> <br/>
<a href="javascript:void(0)" onclick="ScrollTo('destination1', 500)" style="font-weight:bold; color:green; text-decoration:none" title="Scroll to Bottom">I'M GOING TO THE DESTINATION 1</a>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<p id="destination1" style="font-weight:bold; color:green;">THE DESTINATION 1</p>
</center>
</body>
</html>


You just need to change the id and of course, you need to define it first. Just like the below.
<p id="destination" style="font-weight:bold; color:red;">THE DESTINATION</p>

<a href="javascript:void(0)" onclick="ScrollTo('destination', 500)" style="font-weight:bold; color:red; text-decoration:none" title="Scroll to Top">I'M GOING TO THE DESTINATION</a>

See it live here.

Popular posts from this blog

Set table width to 100% on PDF export in Datatables

Hot/Cute flat-chested Girls