You can use the scrollTo
function, as follows:
window.scrollTo(DOMNodeOfMyNewMessage.offsetTop,window.scrollY);
This will scroll the latest message to the top of the screen.
However, you’ll probably want to scroll the page just by the height of the new comment. That is possible too, using the scrollBy
function and the element’s offsetHeight
:
window.scrollBy(DOMNodeOfMyNewMessage.offsetHeight, window.scrollY);
The final code might look somewhat like the following:
var jsChat = {
username: document.getElementById('username'),
comment: document.getElementById('comment'),
output: document.getElementById('output'),
},
latestMessage;//DOM Node of my new message
function postData(){
latestMessage = document.createElement('div');
latestMessage.innerHTML = '<div class="username">' + jsChat.username.value + ':</div>' +
'<div class="comment">' + jsChat.comment.value + '</div>';
clearContent();//Not sure what this does, check if you still need it with this code
latestMessage = jsChat.output.appendChild(latestMessage);// appendChild: see https://developer.mozilla.org/docs/Web/API/Node.appendChild
//Now we scroll the message into view
window.scrollBy(latestMessage.offsetHeight, window.scrollY);
}