1

I read in here ( Prevent BODY from scrolling when a modal is opened ) that this...

body.modal-open {
    overflow: hidden;
}

...will prevent scrolling underneath a Bootstrap modal. Or is that supposed to be the default setting already? (not sure) For some reason, I cannot get this to work. I'm using the latest version of Bootstrap in my Rails app. Has Bootstrap changed this again?

In the Bootstrap docs, it says... "The modal plugin toggles your hidden content on demand, via data attributes or JavaScript. It also adds .modal-open to the <body> to override default scrolling behavior and generates a .modal-backdrop to provide a click area for dismissing shown modals when clicking outside the modal."

The .modal-backdrop for dismissing modals on clicking the backdrop does actually work, but as I'd said, the overriding of the scrolling does NOT work. Very strange, because in my other Rails app, the overriding of the scrolling underneath DOES work, while the dismissing modals on clicking the backdrop does NOT work. Very strange because I appear to have implemented them identically.

Adding position: fixed; to my CSS does indeed stop the scrolling underneath the modal, but unfortunately, it causes the body to jump to the top. I want the body to remain in the same vertical position no matter where I open a modal. Any help much appreciated. Thanks.

Community
  • 1
  • 1
Matt
  • 811
  • 2
  • 11
  • 20

1 Answers1

0

I actually got it to work with some help from 'ling' in Prevent BODY from scrolling when a modal is opened. I used his CSS and then did this for my JS (an adaptation of ling's JS)...

// Prevent scrolling underneath Bootstrap modals
$( document ).ready(function() {
  $("a.modal-initiator").on("click", function() {
    currentScrollTop = $(window).scrollTop();
    $('html').addClass('noscroll').css('top', '-' + currentScrollTop + 'px');
  });

  $(".close-modal").on("click", function() { // modal 'close' buttons
    resumeScrollingAferModal();
  });

  $("#modal").on("click", function(e) { // grey area outside modal
    if( !$(e.target).is('modal-content') ) {
      resumeScrollingAferModal();
    }
  });

  function resumeScrollingAferModal() {
    $('html').removeClass('noscroll');
    $(window).scrollTop(currentScrollTop);
  }
});

Unfortunately I did not know how to avoid using a global variable, 'currentScrollTop'. I'm still curious as to why the normal Bootstrap functionality for modals did not work for me....

Community
  • 1
  • 1
Matt
  • 811
  • 2
  • 11
  • 20