Reputation: 1474
We all know the solution to scroll to a position from the top of the viewport:
$("html, body").animate({scrollTop:240}, 'fast');
Is there a way to scroll similar to scrollTop, just from the bottom of the viewport?
What I want to do: on a click event the page should scroll to a div anywhere in the body, it should stop scrolling when the div has reached the bottom of the viewport, fully visible. Is that possible?
Upvotes: 0
Views: 477
Reputation: 50115
You need to use a combination of .offset().top
, which is the offset of the element from the top of the document, and $(window).height()
, which is the height of the viewport:
var b = $('myEle');
$('html').animate({scrollTop: b.offset().top - $(window).height() + b.outerHeight()});
Scrolling to the oft-used .offset().top
position will get the block to move to the top of the screen, so we simply minus off the height of the viewport and add the height of the object to get it to shift to a position at the bottom of the user's viewport.
See a simple demo here: http://www.jsfiddle.net/yijiang/Xkj9s/
Upvotes: 2
Reputation: 70701
There's a scrollHeight
property that tells you the amount you can scroll. So if you want to scroll 240 px from the bottom, use scrollHeight - 240
, for example:
var elem = $('html');
elem.animate({ scrollTop: elem[0].scrollHeight - 240 }, 'fast');
Upvotes: 1