I have a div, and I’m reloading it with Ajax every 1 second. And it has auto value as overflow. To keep my div always bottom, I’m using a javascript code in Ajax request.
xmlHttp.onreadystatechange=function(){
document.getElementById('chatting').scrollTop = 9999999;
if(xmlHttp.readyState==4){
document.getElementById('chatting').innerHTML=xmlHttp.responseText;
setTimeout('Ajax()',1000);
}
}
var withdate=document.getElementById('firstdate').value;
nocache = Math.random();
xmlHttp.open("GET","db.getMessages.php?date=" + withdate + "&nocache = "+nocache,true);
xmlHttp.send(null);
}
window.onload=function(){
setTimeout('Ajax()',1000);
}
But I can’t select texts and can’t go upper. When the new content is loaded, div slides bottom. How can I solve this?
I’ve a question too. I’m using a PHP file to define json contents. And output is like this:
{ "msg": [{"from":"demo","text":"test message "} ] }
But Firebug shows this error to me:
Error: JSON.parse: unexpected character
Source File: http://localhost/script/script/json.js
Line: 20
Line 20 is:
var msgs = JSON.parse(xhr.responseText);
I struggle so much but haven’t solve 🙁
You replace the whole chatting-Element and expect the browser to remember and keep the selection?
I guess you’re implementing a simple chat client, right? Then, why don’t you just pull new messages instead of, I guess, all? Return all messages as JSON and create DOM-nodes on your own which you append to the chatting-element. That approach allows you to select content as it never changes and keeps traffic down.
btw:
nocache-Parameters are usually done using a timestamp, because time is always increasing. A Math.random() is not guaranteed to be unique.