I have a modal window and need to be able to open the modal and then scroll the user to a specific spot in the modal.
I am getting the modal contents with AJAX to a PHP script.
eg mypage.php?loc=someid
In the PHP script I have this JS to do the scrolling:
$( document ).ready(function() {
$('.modal-body').animate({
scrollTop: $("#<?php echo $_GET['loc'];?>").offset().top
}, 1000);
});
in the PHP page is some HTML like this:
<div id="someid"></div>
My content loads correctly but the amount of scroll that happens appears to be relative to the link that opened the modal so it does not actually find the div in the doc.
I am guessing my JS needs a little tweaking.
It seems I need to be able to calculate the offset of the element from the top of the modal content.
I can fake this by setting the value against the element I am scrolling to like this. But I really need a programmatic way of calculating this. Obviously different devices will not work correctly as shown.
$( document ).ready(function() {
$('.modal-body').animate({
scrollTop: $("#<?php echo $_GET['loc'];?>").attr('distance')
}, 1000);
});
//Trying to find out how far this div is from the top of the modal window?
<div id="someid" distance="670"></div>
Use the . modal-dialog-scrollable class to enable scrolling inside the 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.
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.
User found solution but doesn't appear to have added it, so for the sake of completeness, here it is
$( document ).ready(function() {
setTimeout(function() {
var $el = $("#<?php echo $_GET['loc'];?>")
var elpos = $el.position();
$('.modal-body').animate({
scrollTop: elpos.top
}, 1000);
},500);
});
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