0

I'm making an instant chat service using PHP and Async javascript. Messages are taken from a database and placed into a text area. The problem is that when messages require the textarea to scroll the setInterval() function used to check and grab new messages forces the text area back to the top of its scrolling height.

I've seen a few solutions and none have worked so far. I tried setting the scrollTop to equal the scrollHeight, but to no avail.

Here's some code:

window.onload = function()
{
    if(getUrlVars()['to'] != null)
        setInterval(GetMessages, 1000);
}

function ToServer(cmd, data)
{
    xmlObj = new XMLHttpRequest();
    xmlObj.open('POST','handler.php',true);
    xmlObj.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xmlObj.send(cmd + data);
    xmlObj.onreadystatechange = function()
    {
        if(xmlObj.readyState == 4 && xmlObj.status == 200)
        {
            if(cmd == 'cmd=push')
            {
                document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
            }
            if(cmd == 'cmd=pop')
            {
                document.getElementById('messages').value += xmlObj.responseText;
            }

        }
    }
}

function GetMessages()
{
    // Grab account hash from auth cookie
    aHash = readCookie('privateChat');
    to = getUrlVars()['to'];
    ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
    textArea = document.getElementById('messages');
    textArea.scrollTop = textArea.scrollHeight;
}

And here's the HTML:

<!DOCTYPE HTML>

<html>

<head>
    <meta charset="ISO-8859-1">
    <title>Private Chat</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <div>
        <h2>Conversation with {%RECIPIENT%}</h2>
        <div id="fieldContainer">
            <textarea col="10" rows="5" name="messageBox" id="messages"></textarea>
        </div>
    </div>

    <div>
        <legend>Message</legend>
        <div id="fieldContainer">
            <input type="text" id="msgBox">
        </div>
    </div>
    <div>
        <input type="button" name="fSend" value="Send message" onClick="SendMessage();">
    </div>
    <div id="pushResponse">Response</div>

    <script src="Chat.js"></script>
</body>

</html>

Thanks!

4

0 回答 0