Div scrolling to top after contents are refreshed/reloaded

Go To StackoverFlow.com

0

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;
    }
});
2012-04-03 22:35
by DobotJr
I am checking the checkmark to answer my questions. Is there another way to mark something as having an answer - DobotJr 2012-04-04 16:45


1

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);
});
2012-04-03 22:50
by Selvakumar Arumugam
Marked this answer but I did have to change a few things to get it to work for me. Look at my Edi - DobotJr 2012-04-04 16:42


0

I think if you don't replace the content and only append the new information to the container that would simply work.

http://api.jquery.com/jQuery.get/

http://api.jquery.com/append/

2012-04-03 22:50
by Sebastian Stiehl