Scroll to the bottom of the page only if the user has already been down before manipulating the DOM

I would like to know how to use window.scrollTo.

Here is the desired behavior:

  • Determine whether the user scrolls at the bottom of the page or not.
  • Then I want to grow a div, it works
  • If # 1 is true, use window.scrollToto scroll to the bottom of the page after increasing the DIV that changed the height of the window.

Ideas?

+3
source share
3 answers

Working with the Han idea, we can determine if the window below scrolls:

$('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/

+2
$(window).scrollTop(document.body.scrollHeight);

: http://jsfiddle.net/nQntc/

0

First you will need to check if you are at the bottom of the page or not. Using Gaby's answer to Definition while scrolling to the bottom of the page using Javascript :

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

You can then manipulate the DOM and scroll to the bottom if the value returned scrollbarAtBottomwas 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;
0
source

Source: https://habr.com/ru/post/1777806/


All Articles