Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to element inside modal window

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>
like image 780
BobB Avatar asked Mar 07 '14 21:03

BobB


People also ask

How do I add a scroll in modal popup?

Use the . modal-dialog-scrollable class to enable scrolling inside the modal.

How do I make modal content scrollable?

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.

How do you make a modal not scrollable?

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.


1 Answers

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);
    });
like image 168
Rob Quincey Avatar answered Sep 30 '22 19:09

Rob Quincey