1

I want to detect if user scrolled to the end of the window then make a trigger click to a "show more" button like Facebook newsfeed.

$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() == $(document).height()){
        $('.feed-show-more-button').trigger('click');
    }
});

this is my code but it's not working only if i scrolled to the end of the window then go back to the top

Anyone can help ?

MimoudiX
  • 612
  • 3
  • 16
Alex
  • 89
  • 7
  • Possible duplicate of [Check if a user has scrolled to the bottom](https://stackoverflow.com/questions/3898130/check-if-a-user-has-scrolled-to-the-bottom) – ABC Mar 17 '19 at 22:04

2 Answers2

1

Try this

var CheckIfScrollBottom = debouncer(function() {
    if (getDocHeight() == getScrollXY()[1] + window.innerHeight) {
        $('.feed-show-more-button').trigger('click');
    }
}, 500);

document.addEventListener('scroll', CheckIfScrollBottom);

function debouncer(a, b, c) {
    var d;
    return function() {
        var e = this,
            f = arguments,
            g = function() {
                d = null, c || a.apply(e, f)
            },
            h = c && !d;
        clearTimeout(d), d = setTimeout(g, b), h && a.apply(e, f)
    }
}

function getScrollXY() {
    var a = 0,
        b = 0;
    return "number" == typeof window.pageYOffset ? (b = window.pageYOffset, a = window.pageXOffset) : document.body && (document.body.scrollLeft || document.body.scrollTop) ? (b = document.body.scrollTop, a = document.body.scrollLeft) : document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop) && (b = document.documentElement.scrollTop, a = document.documentElement.scrollLeft), [a, b]
}

function getDocHeight() {
    var a = document;
    return Math.max(a.body.scrollHeight, a.documentElement.scrollHeight, a.body.offsetHeight, a.documentElement.offsetHeight, a.body.clientHeight, a.documentElement.clientHeight)
}
MimoudiX
  • 612
  • 3
  • 16
1

Added jsfiddle http://jsfiddle.net/3unv01or/

var processing;

$(document).ready(function(){

    $(document).scroll(function(e){
        if (processing)
            return false;

        if ($(window).scrollTop() >= ($(document).height() - $(window).height())){
            console.log('in it');
            processing = true;
            $('#container').append('More Content Added');
            console.log($('#container'));
            processing = false;
            });
        }
    });
});
.loadedcontent {min-height: 800px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">Hello world<div class="loadedcontent"></div></div>
Hiteshdua1
  • 2,126
  • 18
  • 29