How to restore scroll position of updated div in jQuery?

I have a very large div that makes the page scroll bars vertically and horizontally.

Every few minutes I want the contents of the div to be updated, so I use jquery get to reload the contents of the div into the div.

The trap is that I don’t want the place on the screen that the user was looking for to change, I want the div to reload, but the user should still look at the same place in the div (which means the div should not scroll back to (0,0).

What sometimes happens when rewriting html in a div with $ ("#mainwrapper") .html (data) ;, the div is momentarily empty, so it is compressed and then refilled, but the user is now at (0,0)

Hope this makes sense.

+6
source share
1 answer

Before loading content into a div, save the scroll position.

var scroll_l = $('#yourdiv').scrollLeft(), scroll_t = $('#yourdiv').scrollTop(); 

Each time you scroll through a div, keep the sothat position by scrolling when the load is also saved.

 $('#yourdiv').scroll(function() { if ($('#yourdiv').html().length) { scroll_l = $('#yourdiv').scrollLeft(); scroll_t = $('#yourdiv').scrollTop(); } }); 

Then load the new content and reapply the scroll position:

 $('#yourdiv').load('/your/url', function() { $('#yourdiv').scrollLeft(scroll_l); $('#yourdiv').scrollTop(scroll_t); }); 
+8
source

Source: https://habr.com/ru/post/975763/


All Articles