Got a Div being refreshed every 5 seconds. The div has scrolling set to scroll so that user can scroll, but when the refresh happens the div scrolling goes back to the top. Any ideas how I can keep the scroll position after the div is refreshed?
Here's my CSS:
#alerts_container {
height: 150px;
width: 250px;
overflow: scroll;
overflow-x: hidden;
border-right-width: 1px;
border-right-style: solid;
border-right-color: #666;
}
JS:
refresh_alerts = setInterval(function (){
$('#leftside div#alerts_container').load('staffhome.php #alerts_container' );
}, 5000)
HTML:
<div id='alerts_container'>
<?php
include_once('includes/my_alerts.php');
?>
</div>
Used SKS's answer to get this to work for me, but I did have to change his code up a bit:
var isScrolling = false;
var lastScrollPos = 0;
var counter = 0;
$(function() {
$('#alerts_container').bind("scroll", function (){
isScrolling = true;
});
refresh_alerts = setInterval(refreshContent, 5000);
function refreshContent() {
lastScrollPos = $('#alerts_container').scrollTop();
if (!isScrolling) {
$('#alerts_wrapper').load('staffhome.php #alerts_container', function () {
$('#alerts_container').scrollTop(lastScrollPos);
});
}
isScrolling = false;
}
});
You should get scroll height inside your scroll handler using .scrollTop
and then set it after .load
DEMO -- Try scrolling all the way down and wait 5 secs for the new contents to get updated.
Below is an abstract from the demo,
var lastScrollPos = 0;
$('#scrollingDiv').on('scroll', function() {
lastScrollPos = this.scrollTop;
});
and in .load
callback
$('#leftside div#alerts_container').load('staffhome.php #alerts_container' , function () {
$(this).scrollTop(lastScrollPos);
});
I think if you don't replace the content and only append the new information to the container that would simply work.