When I open a modal window it scrolls the background context all the way up to the top. Example I have links on the bottom of the page that open a modal window. When I click on the link the window will scroll up to the top of the document then display the modal window. I have no problem with the positioning of the modal window. I just don't want the scroll up to occur before it opens the page. I'm using mostly the default CSS that came from BS v3 (latest on github) and pretty much the default modal body. I am using JS to populate the label and body of the modal then opening it
<!-- Modal -->
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body" id="myModalBody"></div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Approach: A simple solution to this problem is to set the value of the “overflow” property of the body element to “hidden” whenever the modal is opened, which disables the scroll on the selected element.
If we know the top of the scroll location and add it to our CSS, then the body will not scroll back to the top of the screen, so problem solved. We can use JavaScript for this by calculating the scroll top, and add that value to the body styles: // When the modal is shown, we want a fixed body document.
Use the . modal-dialog-scrollable class to enable scrolling inside the modal.
I had the same problem. I had a button calling a javascript function to open the modal:
<a href="#" onclick="myFunction(id)">open modal</a>
and changed it to:
<a href="javascript:void(0)" onclick="myFunction(id)">open modal</a>
and this solved the scrolling to top problem.
I am using bootstrap 3.3.7 I believe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With