Programming Tree
Programming Tree

Reputation: 125

Scroll to near the bottom of page

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?

Upvotes: 2

Views: 90

Answers (3)

Arun Sharma
Arun Sharma

Reputation: 1331

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>

Upvotes: -1

Nicholas Pedroso
Nicholas Pedroso

Reputation: 1

Try

$(document).scrollTop(($(document).height() - [the offset you want]));

Upvotes: 0

Jamie Counsell
Jamie Counsell

Reputation: 8103

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);

Upvotes: 3

Related Questions