简体   繁体   中英

How to update html table without disturbing scroll position?

HTML:

<div class="html_table"></div> # In html body tag.

Ajax function to get table data.

var $html_table= $('.html_table');
function ajaxCallFunction() { $.ajax({
            type: 'POST',
            url: url,
            contentType: 'application/json',
            success: function(res, status, xhr){
                $html_table.html(res['html_table']);              
            },
            error:function(xhr, status, error){
            }
          });

Updating table for every 5 seconds,

    window.onload = function() {            
      ajaxCallFunction();

    setInterval(ajaxCallFunction, 1000*5);
}

Issue:

I have 100 rows in a table. Need to update it every 5 seconds without disturbing the position of scroll. When the user looking to the bottom line, the scroll bar goes to its original position after 5 seconds. How to handle the issue?

How to update the cell value of the table, without affecting the scroll position?

Any other suggestions are welcome.

Note:

In my case, its more important that focus on current row should not get affected.

You can save the current scroll position before changing the html and restore it after you changed the html.

var savedScrollPosition = $(window).scrollTop;

in response callback then restore the position:

$(window).scrollTop(savedScrollPosition);

If the requested HTML is different from the previous one this is of course not working. Maybe you could calculate the real new scroll position relative to the height of the old and new HTML and the saved scroll position in such a case.

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