Use jquery animate to create a smooth scroll effect (which can be to the top bottom or specified place)

  • 2020-03-30 03:07:08
  • OfStack

Anchors are handy for jumping around a page, but to add to the effect, use jquery's animate, which lets you scroll around an action and slowly scroll to where you want to jump to.

Scroll to the top:

$('.scroll_top').click(function(){$('html,body').animate({scrollTop: '0px'}, 800);});

Scroll to the specified location:

$('.scroll_a').click(function(){$('html,body').animate({scrollTop:$('.a').offset().top}, 800);});


Complete example source reference:


<!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=utf-8" />
<title>js Smooth scroll to the top, bottom, and specified places </title>
<script type="text/javascript" src="http://cdn.staticfile.org/jquery/2.1.1-rc2/jquery.min.js"></script>
<style>
 .box{ height:200px; width:100%; background:#ccc; margin:10px 0;}
 .location{ position:fixed; right:0; bottom:10px; width:20px; background:#FFC; padding:5px; cursor:pointer;color:#003};
</style>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box a"> Product introduction product introduction product introduction product introduction product introduction product introduction product introduction product introduction product introduction product introduction product introduction </div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box bottom"></div>
<div class="location">
  <p class="scroll_top"> Return to the top </p>
  <p class="scroll_a"> Product introduction </p>
  <p class="scroll_bottom"> Slide to the bottom </p>
</div>
<script type="text/javascript">
 jQuery(document).ready(function($){
  $('.scroll_top').click(function(){$('html,body').animate({scrollTop: '0px'}, 800);}); 
  $('.scroll_a').click(function(){$('html,body').animate({scrollTop:$('.a').offset().top}, 800);});
  $('.scroll_bottom').click(function(){$('html,body').animate({scrollTop:$('.bottom').offset().top}, 800);});
 });
</script>
</body>
</html>


Related articles: