How to listen to scroll event on a Bootstrap modal?
Asked Answered
B

2

9

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.

Benignity answered 23/2, 2017 at 19:2 Comment(0)
P
13

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).

Punkah answered 24/2, 2017 at 3:30 Comment(3)
Man, you are a life saver :) – Benignity
@Punkah How would you do this in React? – Miscellany
@Miscellany sorry I've just heard about react but never learnt or experienced with it. – Punkah
K
0

>> BOOTSTRAP 5.x >> FULL SCREEN MODE

if you are using .modal-fullscreen in modal dialog, then scroll Listener for .getElementById('myModalID') will not work! because the dialog itself stands still, and the scrolling happens only inside the modal body

everything worked after I added a listener to the modal-body:

document.querySelector('#myModalID .modal-body')
        .addEventListener('scroll', function(event) {
            console.log("Scrolling");
        });

--

P.S. I spent a lot of time not understanding why .querySelector('.modal-body') didn't work until I realized that I have multiple dialogs on the page πŸ€¦β€β™‚οΈ and .querySelector gets the wrong dialog πŸ€·β€β™‚πŸ˜

Keldon answered 3/3, 2023 at 22:33 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.