Joshua Dickerson Joshua Dickerson - 6 months ago 40
jQuery Question

Modal With Another Modal Causes Scroll on Body

https://jsfiddle.net/e6x4hq9h/

Open the first modal. It opens fine. Removes the background scrollbar.

Open the modal from within that modal. It causes the scroll to go to the background.

I searched for other solutions and none of them seem to fix this. I tried everything on this page: Bootstrap modal: close current, open new among others.

Javascript:

// Only one of these modals should show at a time.
$('#myModal2').on('show.bs.modal', function (e) {
$('#myModal').modal('hide');
})
.on('hide.bs.modal', function (e) {
$('#myModal').modal('show');
});


Update: The first and second modal must also allow scrolling as can be seen in this fiddle: https://jsfiddle.net/e6x4hq9h/21/

Answer

To elaborate further on Hardik response, what essentially is happening is a hard-coded, inline declarations for the .modal-open class to the body element. However, the .modal-open class, also has a nested declaration for .modal-open .modal where it sets the overflow-y property for the modal to be "auto" -- hence why it is scrollable. To accomplish this, add .css("overflow-y", "auto") to the modal that will be opened. This is what it would look like based off your fiddle:

$(document).ready(function () {

    // Only one of these modals should show at a time.
    $('#myModal2').on('show.bs.modal', function (e) {
        $('#myModal').modal('hide');
        $('body').css("overflow","hidden");
        $(this).css("overflow-y", "auto");
    })
    .on('hide.bs.modal', function (e) {
        // @todo reload the job
        $('#myModal')
            .modal('show')
            .css("overflow-y", "auto");
    });

    $('#myModal').on('show.bs.modal', function (e) {
        // @todo reload the job
        $('body').css("overflow","hidden");
    })
    .on('hide.bs.modal', function (e) {
        // @todo reload the job
        $('body').css("overflow","visible");
    });
});

Results viewable here: https://jsfiddle.net/e6x4hq9h/22/

Comments