2

How do I scroll near the bottom of a page. I'm using the following code to scroll to the very bottom:

$(document).scrollTop($(document).height());

How do I change this code to scroll near the bottom?

  • can you give us a reason on why you want *near* and not *exactly* the bottom? Because that may help a lot. – Jhecht Apr 29 '16 at 21:22
  • @Jhecht I'm making an endless content application. When the user scrolls to the bottom, more content loads. I want the user to be near the bottom when they scroll, but not load more content... – Programming Tree Apr 29 '16 at 21:23
  • so you want for it to scroll to like... the last current item before loading more? – Jhecht Apr 29 '16 at 21:32

3 Answers3

3

How near?

$(document).scrollTop($(document).height() - 1000);

Will scroll close to the bottom. The problem here is that you have to consider the height of the viewport as well.

A good, cross browser way to get the viewport height is:

var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)

then:

var offset = 100;//your offset. 100px from the bottom here

$(document).scrollTop($(document).height() - (height + offset);
Community
  • 1
  • 1
Jamie Counsell
  • 7,730
  • 6
  • 46
  • 81
0

Try

$(document).scrollTop(($(document).height() - [the offset you want]));
Bijan
  • 7,737
  • 18
  • 89
  • 149
-1

Your code is correct but the document height must be greater than the window height for this to work.

$(document).ready(function(){
    $("button").click(function(){
      var offset = 500;
      var scrollX = $(document).height() - offset;
      alert(scrollX);
      $(document).scrollTop(scrollX);
    });
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body style="height:1500px">

<p>lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum lorem Ipsum </p>

<button>Scroll to bottom</button>

</body>
</html>
Arun Sharma
  • 1,331
  • 8
  • 11