简体   繁体   中英

Keep scroll position inside div after reload php file with ajax

I have a div with it's own scroll bar which is being reloaded by AJAX (php file). When I scroll inside this div and reload it, the inner scrollbar gets sent back to the top. I would like for the scroll bar to remain at the position where I originally scrolled to.

<style>
    #div2 {
        height: 400px;
        width: 100%;
        overflow-y:scroll;
    }
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
    setInterval(function () {
        $('#div1').load('shownic8.php');
    },7000);
</script>
<div id="div1">
</div>

Here is the code from "shownic8.php" file

<div id="div2">
...
</div>

Can you help me keep the position of my scroll bar? Thank you very much.

Check https://api.jquery.com/scrolltop/

  1. Before .load() store current scroll position:

    var pos = $('#your-container').scrollTop();

  2. Use .load() callback ( http://api.jquery.com/load/ ) to restore scroll position:

    $('#your-container').scrollTop(pos);

Using your code:

        setInterval(function () {
            var scrollTarget = $('#div1');
            var pos = scrollTarget.scrollTop();
            scrollTarget.load('shownic8.php', function() {
                $('#div1').scrollTop(pos);
            });
        },7000);

You can either use DOM element's scrollTop property or jQuery function of the same name.

But I don't advice you to do so because saving and restoring scroll position you couldn't avoid a slight blinking effect every time you reload contents.

So, instead, I would recommend to update items that actually change instead of reloading the whole contents, so the scrollTop property gets never changed.

Of course, (to do it the right way) it implies modifying your shownic8.php page (or implementing another different route instead) to return some structured data and use them to fill or update your div contents.

On the other hand, you can try another, slightly dirty, approach to hide that blinking efect (replacing it by a less obvious side effect). That is:

  1. Instead of loading your contents directly into #div1 element, create a new div inside it (appending through .append() or .appendTo() ) and load into it.

  2. After that (at least in reloading operations), remove previous contents so that new content climbs up to the top position (and not altering scroll position).

Example: (untested)

setInterval(function () {
    var prevContents = $("#div1>*");
    $('<div></div>')
        .load('shownic8.php')
        .appendTo('#div1')
    ;
    prevContents.remove();
},7000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM