javascriptjqueryhtmlajaxscrolltop

How to stop scrolling to top after an ajax call


I update a certain content of htm element with setInterval function to call an ajax every few sec

<div class="content">
<p>New informaton here</p>
<br>
<p>.......</p>
more information below
</div>

below is the javascript

var main = function(){
        updatingMessage = setInterval(function(){
         $.ajax({
        type: "POST",
        url:" call_MYSQLDatabase_To_Update_Content.php",
        cache:0,
        data:({
           some vars
             }),
        success:function(result){
         $(".content").html(result);
                          }
                 });  
                       }, 1000);
     updatingMessage();
        }
$(document).ready(main);

What's bother me is everytime when I scroll down to see the information it will scroll to the top of itself after each ajax call.
Is there anyway to stay at the same <p>'s position after an ajax call ?


Solution

  • First you must get the element's scroll position, then make sure you maintain that position by setting the scrollTop attribute to the original position.

    var position = element.scrollTop;
    
    //do some work here, which might change the position
    
    element.scrollTop = position;