Scroll to bottom of page, only if the user already was at the bottom before DOM manipulation
I'd like to learn how to use window.scrollTo
.
Here's is the desired behav开发者_如何学Goior:
- Determine if the user is scrolled to the bottom of the page, or no scroll bar is visible
- Then I want to grow a DIV, this is working
- If #1 was true, use
window.scrollTo
to scroll to the bottom of the page after the DIV has grown which changed the window height.
Ideas?
Working from Han's idea, we can detect whether the window is scrolled to the bottom like this:
$('button').click(function(){
var shouldScroll = $(document).scrollTop() + $(window).height() === $(document).height();
$('<div>added content</div>').appendTo('body');
if(shouldScroll) {
$(window).scrollTop(document.body.scrollHeight);
}
});
Updated jsFiddle here: http://jsfiddle.net/JamesKovacs/nQntc/1/
First, you'll have to check whether you're at the bottom of the page or not. Using Gaby's answer to Determining when scrolled to bottom of a page with Javascript I get:
function scrollbarAtBottom() {
var totalHeight, currentScroll, visibleHeight;
if (document.documentElement.scrollTop)
currentScroll = document.documentElement.scrollTop;
else
currentScroll = document.body.scrollTop;
totalHeight = document.body.offsetHeight;
visibleHeight = document.documentElement.clientHeight;
if (totalHeight <= currentScroll + visibleHeight)
return true;
else
return false;
}
Next, you can manipulate the DOM and scroll to the bottom if the value returned by scrollbarAtBottom
was true
:
var atBottom = scrollbarAtBottom();
/* do some stuff */
if (atBottom)
if (document.documentElement.scrollTop)
document.documentElement.scrollTop = document.documentElement.clientHeight;
else
document.body.scrollTop = document.body.clientHeight;
$(window).scrollTop(document.body.scrollHeight);
Test case: http://jsfiddle.net/nQntc/
精彩评论