Search code examples
javascriptjquerytwitter-bootstrapbootstrap-modalinfinite-scroll

How to detect position of the Bootstrap modal scrollbar?


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?


Solution

  • 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');
        } 
    
    });