Using jQuery to achieve the intelligent hiding sliding effect of the return to the top code

  • 2020-03-30 02:22:21
  • OfStack

  Online DEMO: (link: http://demo.jb51.net/js/2014/return-top/)

HTML code (placed anywhere on the page and beautified with CSS) :

<p id="back-to-top"><a href="#top"><span></span> Back to the top </a></p>

JS code:


<script type="text/javascript" src="js/jquery-1.7.2.min.js">
</script>
<script type="text/javascript">
  $(document).ready(function() {
    //First, hide #back-to-top
    $("#back-to-top").hide();
    //When the scroll bar is below 100 pixels from the top, the jump link appears, otherwise it disappears
    $(function() {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
          $("#back-to-top").fadeIn(1500);
        } else {
          $("#back-to-top").fadeOut(1500);
        }
      });
      //When you click the jump link, go back to the top of the page
      $("#back-to-top").click(function() {
        $('body,html').animate({
          scrollTop: 0
        },
        1000);
        return false;
      });
    });
  });
</script>

Here's a simpler code to go back to the top:

First see demo: (link: http://demo.jb51.net/js/2016/gotop/)

Complete code:


<!DOCTYPE html>
<html>
<head>
<title> Based on the jquery Returns the top effect </title>
<script type="text/javascript" src="http://img.jb51.net/jslib/jquery/jquery.min.js"></script>
<style type="text/css">
#goTop{position:absolute;display:none;width:50px;height:48px;background:#fff url(//files.jb51.net/file_images/article/201601/gotop.png) no-repeat 16px 15px;border:solid 1px #f9f9f8;border-radius:6px;box-shadow:0 1px 1px rgba(0, 0, 0, 0.2);cursor:pointer}
#goTop:hover{height:50px;background-position:16px 16px;box-shadow:0 1px 1px rgba(0, 0, 0, 0.3)}
</style>
</head>
<body>
<div style="height:2000px; text-align:center; padding-top:300px"> To see this, drag the scroll bar down to the bottom right corner </div>
<div id="goTop" class="goTop"></div>
<script type="text/javascript">
	$(window).scroll(function(){
		var sc=$(window).scrollTop();
		var rwidth=$(window).width()+$(document).scrollLeft();
		var rheight=$(window).height()+$(document).scrollTop();
		if(sc>0){
			$("#goTop").css("display","block");
			$("#goTop").css("left",(rwidth-80)+"px");
			$("#goTop").css("top",(rheight-120)+"px");
		}else{
			$("#goTop").css("display","none");
		}
	});
	$("#goTop").click(function(){
		$('body,html').animate({scrollTop:0},300);
	});
</script>
</body>
</html>

Related articles: