简体   繁体   中英

scroll to bottom of the div doesn't work

function ereja(){
  var newscrollHeight2 = $("#messages")[0].scrollHeight;
  return newscrollHeight2;
}

var newscrollHeight = ereja();
var oldscrollHeight = $("#messages")[0].scrollHeight;

function merrmesazhet(){
  $('#messages').load(
    "nxirr_mesazhet.php?room=<?php echo urlencode($dhoma24); ?>"
  );     
  setTimeout(ereja, 1000);
  if( newscrollHeight != oldscrollHeight ){ 
    $("#messages").scrollTop($("#messages")[0].scrollHeight); 
  }
}

What's wrong with this code? Why it doesn't work? I am trying to scroll to bottom of the div when a user writtes a new message. Any idea?

Assuming you are actually calling merrmesazhet() and that you are testing on IE>=8 as lower versions don't support scrollHeight . Then your main issue is the use of setTimeout which is essentially calling ereja every second and doing nothing .

Indeed you do not even need the JS timer - you are using jQuery which supports a callback in it's load function (which executes once on a successful load rather than repeatedly). Your if-statement in it's current form will always evaluate to false as it isn't within the function executed on the timer anyway.

Something like this may work for you:

var oldscrollHeight = $("#messages")[0].scrollHeight;

function merrmesazhet(){
    $('#messages').load(
        'nxirr_mesazhet.php?room=<?php echo urlencode($dhoma24); ?>',
        function(){
            var newscrollHeight = $("#messages")[0].scrollHeight;
            if( newscrollHeight != oldscrollHeight ){
                $("#messages").scrollTop($("#messages")[0].scrollHeight);
            }
        }
    );
}

jsFiddle

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