简体   繁体   中英

only scroll to bottom if user not scrolling

I find myself getting frustrated with JS yet again! please help!

below is some code I am using for a simple chat app, that refreshes the content from a text file via an AJAX request. At the same time it scrolls to the bottom of the window. I want it so if the user scrolls up to catch up it doesnt keep interupting this behavour by sending them down to the bottom when it refreshes. How could I do this.

<script>

$(function() {
  startRefresh();  
});
function startRefresh() {
    setTimeout(startRefresh,3000);

    $.post('pollchat.php', function(data) {
         $('#content_div_id').html(data);
         var wtf    = $('#content_div_id');
         var height = wtf[0].scrollHeight;
         wtf.scrollTop(height); 
    });
}
</script>

Any help greatly appreciated.

See How I have used current scroll position and counted that whether user has scrolled or not..

 $(function() { startRefresh(); }); function startRefresh() { setTimeout(startRefresh, 1000); var wtf = $('#content_div_id'); var currentScrollPos = wtf.scrollTop(); var elementHeight = wtf[0].scrollHeight; var scroll = false; //User has scrolled, don't set scroll if (wtf.height() + currentScrollPos >= elementHeight) { scroll = true; } var data = $('#content_div_id').html(); data += "Some Text<br/>"; $('#content_div_id').html(data); if (scroll) { var height = wtf[0].scrollHeight; wtf.scrollTop(height); } } 
 #content_div_id { max-height: 100px; overflow-y: scroll; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content_div_id"> Some Text <br/>Some Text <br/>Some Text <br/>Some Text <br/> </div> 

UPDATE: Try this code, you probably need to fix one or two things .. but have a look at the code and get an idea

$(function() {
  startRefresh();  
});
function startRefresh() {
    setTimeout(startRefresh,3000);

    $.post('pollchat.php', function(data) {
        var wtf = $('#content_div_id');
        var currentScrollPos = wtf.scrollTop();
        var elementHeight = wtf[0].scrollHeight;
        var scroll = false;

        //User has scrolled, don't set scroll
        if (wtf.height() + currentScrollPos >= elementHeight) {
            scroll = true;
        }

         $('#content_div_id').html(data);
         if (scroll) {
            var height = wtf[0].scrollHeight;
            wtf.scrollTop(height);
        }
    });
}

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