Friday, March 30, 2012

Scroll page with javascript

Sometimes it's useful to scroll the page automatically to send users to certain parts of the page. To do that the easiest way is using javascript, more specifically jquery that is a javascript framework.

Test it here:

Scroll down!
 
Example code:

<html>
<head>
<SCRIPT LANGUAGE="JavaScript" 
SRC="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
function scroll_up()
{
    $(window).scrollTop(0);
}
function scroll_to_last_div()
{
    $(window).scrollTop($('#last_div').offset().top);
}
</SCRIPT>
</head>
<body>
<center>
<div style="height:100px;width:400px;">
<br><br>
<a href="javascript:scroll_to_last_div();">Scroll to last div!</a>
</div>
<div style="height:600px;width:400px;background:#234a34;">
</div>
<div style="height:100px;width:400px;" id="last_div">
<br><br>
<a href="javascript:scroll_up();">Scroll to top!</a>
</div>
<div style="height:600px;width:400px;background:#fa342a;">
</div>
</center>
</body>
</html> 

No comments:

Post a Comment