BobB
BobB

Reputation: 772

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>

Upvotes: 9

Views: 7593

Answers (2)

Noel Swanson
Noel Swanson

Reputation: 351

The solution found by the OP and reposted by Rob Quincey works well, HOWEVER do remember that position give you the position relative to the element's parent element.

If the element is a bare <div> it is not problem, but if the grandparent element has some margin or padding properties, then the position of the parent element will be pushed down the page. Which means that the position of this element will also be pushed down. So to the the scrolling to work properly, you need to add the position of the parent element viz:

     $( document ).ready(function() {
        setTimeout(function() {
        var $el = $("#<?php echo $_GET['loc'];?>")
        var elpos = $el.position();
        var elparentpos = $el.parent().position();

        $('.modal-body').animate({
            scrollTop: elpos.top + elparentpos.top;
        }, 1000);

        },500);
    });

And then, if necessary, work your way up the DOM tree until you get to the top element which would normally be your modal div. But you only need to address elements which have some top end margin or padding.

Upvotes: 1

Rob Quincey
Rob Quincey

Reputation: 2896

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);
    });

Upvotes: 3

Related Questions