4

I'd like to learn how to use window.scrollTo.

Here's is the desired behavior:

  1. Determine if the user is scrolled to the bottom of the page, or no scroll bar is visible
  2. Then I want to grow a DIV, this is working
  3. 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?

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

3 Answers3

2

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/

James Kovacs
  • 11,549
  • 40
  • 44
0

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;
Community
  • 1
  • 1
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
-1
$(window).scrollTop(document.body.scrollHeight);

Test case: http://jsfiddle.net/nQntc/

Han Seoul-Oh
  • 1,237
  • 1
  • 12
  • 20