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
  • 879
  • 1
  • 8
  • 12

3 Answers3

2

Using jQuery:

jqEl.scrollTop(jqEl.scrollHeight());

Using DOM:

oEl.scrollTop = oEl.scrollHeight;

fiddle

Brigand
  • 80,366
  • 19
  • 159
  • 169
Roger Barreto
  • 1,896
  • 1
  • 16
  • 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,378
  • 1
  • 18
  • 27
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,081
  • 1
  • 19
  • 27