We will add a jQuery function to create smooth scroll in our anchor links.
jQuery Animate
You can customize the speed of the effect.
Change the 2000 for 1000 (faster) or 5000 (slower).
$(function(){
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, 2000);
return false;
}
}
});
});
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, 2000);
return false;
}
}
});
});
Full Code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example 17 | CodeGround</title>
</head>
<body style="background:url(http://cdn.quicoto.com/codeground/bg.jpg) repeat-x top left;">
<div style="height:1000px; padding:30px;"><a href="#CodeGround">Click me to scroll down!</a></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
$(function(){
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, 2000);
return false;
}
}
});
});
</script>
<a name="CodeGround"></a>
<p style="margin:30px 0px 50px 30px;"><a href="http://php.quicoto.com/how-to-scroll-smoothly-with-jquery">Go back and leave a Comment</a></p>
</body>
</html>
How to scroll smoothly with jQuery
Reviewed by JohnBlogger
on
3:03 PM
Rating:
No comments: