Tạo nút scroll to top cho website dùng jQuery


Từ: 09:57 03/08/2014
Bài: 17
Cảm ơn: 4
Thích: 2

Nội dung của một trang web quá dài, để thuận tiện cho người dùng đỡ phải kéo thanh trượt lên đầu trang thì ta thêm nút back to top (hay scroll to top) tạo sự thuận tiện nhất cho người dùng. Hôm nay tôi sẽ chia sẻ code để làm được nút này.

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 800px">
  Content
  <div id="back-top" title="Top of Page">&uarr;</div>
</div>

 

Javascript

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 300) {
      $('#back-top').fadeIn();
    } else {
      $('#back-top').fadeOut();
    }
  });
  // scroll body to 0px on click
  $('#back-top').click(function() {
    $('body,html').animate({
      scrollTop: 0
    }, 500);
    return false;
  });
});
 

CSS

#back-top {
  border-radius: 5px;
  color: white;
  background: blue;
  padding: 10px;
  position: fixed;
  bottom: 68px;
  right: 25px;
  display: none;
  opacity: 0.8;
  cursor: pointer;
}