0

I'm using JQuery and Bootstrap and I'm loading a modal with an ajax request, so content will be loaded dynamically inside of the modal.

I managed to load more content with a button click (also inside the modal), but I wanted to implement a infinite scroll feature.

However the window.onscroll function didn't seem to work or to recognize the scroll position inside the modal, even if I define it inside the modal after the first ajax request.

Question: How can I detect if a specific element inside the modal is visible to the user to load more content automatically?

AlexioVay
  • 3,158
  • 2
  • 21
  • 41

3 Answers3

3

Actually I found out the right answer myself:

var modal_scrollTop = $('.modal-body').scrollTop();
var modal_scrollHeight = $('.modal-body').prop('scrollHeight');
var modal_innerHeight = $('.modal-body').innerHeight();

$('.modal-body').scroll(function() {

    // Write to console log to debug:
    console.warn('modal_scrollTop: ' + modal_scrollTop);
    console.warn('modal_innerHeight: ' + modal_innerHeight);
    console.warn('modal_scrollHeight: ' + modal_scrollHeight);

    // Bottom reached:
    if (modal_scrollTop + modal_innerHeight >= (modal_scrollHeight - 100)) {
        alert('reached bottom');
    } 

});

Please vote up my question/answer if it helps you.

AlexioVay
  • 3,158
  • 2
  • 21
  • 41
  • I have the same problem but your code is not working for me – pietà Oct 18 '17 at 14:54
  • I've edited my post. Tested and works with Google Chrome and modern Android devices. The `100` means that 100 pixel are the threshold (to activate infinite scroll and load-more-content option in my case). – AlexioVay Oct 19 '17 at 15:34
  • could you please make a jsfiddle ? – pietà Oct 19 '17 at 15:49
2

This should do the trick

const $modal = $("#myModal")
const $bookList = $modal.find('.media-list')

$modal.scroll(e => {
  const $middleBook = $bookList.find('.media').eq(BOOKS_CHUNK_SIZE / 2)
  const middleBookInViewport = $(window).height() > $middleBook.offset().top;

  if(bookChunks.length && middleBookInViewport){
    $bookList.append(bookChunks.shift().map(bookTemplate))
  }
})

jsFiddle

Kamil Latosinski
  • 714
  • 4
  • 23
0

This will work for Bootstrap 4.7, it will trigger a console log command 100px from the bottom of the modal body bottom.

$('.modal-body').bind('scroll', chk_scroll);

function chk_scroll(e) {
    var elem = $(e.currentTarget), offsetHeight = 100;

    if (elem[0].scrollHeight - elem.scrollTop() - elem.outerHeight() <= offsetHeight) {
        console.log('Near the bottom')
    }
}
Andrew Schultz
  • 3,530
  • 2
  • 15
  • 37