View Full Version : How to make the chat box behavior
xuanmanh
Aug 23, 2006, 10:06 PM
Well, I want to create something that behaves just like a chat box like this:
When I add messages to the box (by adding HTML to a <div> using innerHTML entity) at the bottom of the existed message, It scrolls to the new message I've just add. Right now it does not scroll:confused:
Thanks for help!
LTheobald
Aug 24, 2006, 04:23 AM
One question - is this all on one page, or are you using something like an IFRAME? Posting a bit of example code might help us a bit here too.
xuanmanh
Aug 24, 2006, 06:46 PM
This is my sample code:
<style>
.scrollbar{/*I define the div scroll bar here*/}
</style>
<div id=msgs class='scrollbar' style='width:300; height:240'></div>
<script language='javascript'>
var msgline=0;
function addmsg()
{
msgline++;
msgs.innerHTML+="This is the message line "+msgline;
}
</script>
<input type=button value='add msg' onclick='addmsg()'>
Now click 'add msg' to add message into the div tag. And I want the newest message will be scrolled to.
I also want to know if it is possible with iframe or all on one page
Thanks!
LTheobald
Aug 25, 2006, 01:00 AM
Ah good old Google - I found a code example without having to code one myself :)
Right first thing you will need to do is to ensure your div has a height (which it already does in your code) and you also need to set it's overflow property to "scroll":
<style>
.scrollbar{
width: 300px;
height: 200px;
border: 1px solid black;
overflow: scroll;
}
</style>
Now have a look here: http://developer.mozilla.org/en/docs/DOM:element
You'll notice that an element (such as a div) has a series of "offset" & "scroll" width, heights etc. I believe these are what you want to use. Click on OffsetHeight or ScrollHeight and look at the examples they give you (the pictures). This will help you understand exactly what they measure.
Then there's this code example:
http://radio.javaranch.com/pascarello/2006/08/17/1155837038219.html
As you can see from the example, it automatically moves to the bottom or the DIV.
That should get you started - I'll have a tinker with it myself later and see what I come up with.
xuanmanh
Aug 25, 2006, 02:50 AM
Thanks a lot, your work is excellent. That's a good solution