0
<script type="text/javascript">    
var elementshoku = document.getElementById("1on1shoku");
    var lastHeightshoku = elementshoku.scrollHeight;
    function detectChangeshoku(){
        var currentHeightshoku = elementshoku.scrollHeight;
        if(lastHeightshoku != currentHeightshoku){
    alert("xxx");
    elementshoku.scrollTop = currentHeightshoku;
    lastHeightshoku = currentHeightshoku;
        }
    }
    var mesazhet_shoku = setInterval(detectChangeshoku, 200); 
</script>

I am making a chat and I would like to scroll the div to the bottom when a user writes a message. I am using that function, but it is not working. I did put the alert(); function to check if the function above works or not. I have tried many ways, but none of them works. Any idea why it does not work?

Thanks


EDIT:

I see that my question was not clear enough. I am making a chat and I want the div to Auto-scroll to the bottom if there is written e new message. In this answer, it is said to do it this way https://stackoverflow.com/a/7666680/1932887 but it does not work for me. Any idea?

Community
  • 1
  • 1
DjOnce
  • 969
  • 1
  • 8
  • 13

3 Answers3

2

Using jQuery:

jqEl.scrollTop(jqEl.scrollHeight());

Using DOM:

oEl.scrollTop = oEl.scrollHeight;

fiddle

Brigand
  • 84,529
  • 20
  • 165
  • 173
Roger Barreto
  • 2,004
  • 1
  • 17
  • 21
1

You can't request the getElementById("1on1shoku") and read it's scrollHeight before it has been rendered. Put the first lines in the onload like so:

<script type="text/javascript">
var elementshoku, lastHeightshoku;
window.onload=function() {
    elementshoku = document.getElementById("1on1shoku");
    lastHeightshoku = elementshoku.scrollHeight;
}
function detectChangeshoku(){
    var currentHeightshoku = elementshoku.scrollHeight;
    if(lastHeightshoku != currentHeightshoku){
        elementshoku.scrollTop = currentHeightshoku;
        lastHeightshoku = currentHeightshoku;
    }
}
var mesazhet_shoku = setInterval(detectChangeshoku, 200);
</script>
asontu
  • 4,548
  • 1
  • 21
  • 29
1

Try using the jQuery. It helps your code cleaner and easier to understand for future maintenance. By using jQuery you can do it by:

$(window).load(function() {
    $("html, body").animate({ scrollTop: $("#1on1shoku").scrollTop() }, 1000);
});
Sithu
  • 4,241
  • 1
  • 20
  • 28