Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to scroll event on a Bootstrap modal?

I have a really long bootstrap modal like the last example here. I want to detect if user scrolls when the modal is open.

I tried

document.addEventListener('scroll', function(event) {
        console.log("Scrolling");
});

also tried

$(document).on("scroll","#myModalID",function() {
     // I tried targeting .modal-body and .modal-content too
     console.log("Scrolling");
});

and

$(window).on("scroll",function() {
     console.log("Scrolling");
});

All these are working until I open the modal. But when the modal is open none of the above code works. Works again when I close the modal and scroll.

like image 915
Narendran Parivallal Avatar asked Feb 23 '17 19:02

Narendran Parivallal


People also ask

Can you scroll in a modal?

Bootstrap 4.3 added new built-in scroll feature to modals. This makes only the modal-body content scroll if the size of the content would otherwise make the page scroll. To use it, just add the class modal-dialog-scrollable to the same div that has the modal-dialog class.

How do I enable scrolling in modal?

Use the . modal-dialog-scrollable class to enable scrolling inside the modal.


1 Answers

You should notice that the scroll event is not bubbled, so you cannot attach handler on some parent element (like document) or use event delegating with .on in jQuery.

Just select the element directly (because you have its id defined), like this:

document.getElementById('myModalID')
        .addEventListener('scroll', function(event) {
    console.log("Scrolling");
});

Or for jQuery:

$('#myModalID').on("scroll", function() {      
  console.log("Scrolling");
});

That should work (and I've already tried it).

like image 198
Hopeless Avatar answered Sep 16 '22 11:09

Hopeless