1

I want div containing a chat, similar to facebook. If the text content gets longer, ther is y-scroll, but:

  1. The focus shall be on the newest chat entry
  2. A very long word should do a line break

js fiddel code

CSS

.chat{
width: 230px;
    height: 310px;

margin-left: 10px;
background-color: grey;
    border: solid 1px black;

overflow-y:scroll;
}
kaputu
  • 141
  • 2
  • 4
  • 10

2 Answers2

5

You have to scroll to the bottom when a new message comes in and you have to use JavaScript to do it (there might be a clever CSS way I don't know, though).

If you're using jQuery (and I'd recommend you do), you can do it something like this:

// when a new message comes in...
var $chat = $(".chat");
$chat.scrollTop($chat.height());

You might want to change the selector from $(".chat") -- that will probably scroll all chats, which you wouldn't want.

You can also do it with vanilla JavaScript:

// when a new message comes in...
var chatEl = document.getElementById("#mychatelement");
chatEl.scrollTop = chatEl.scrollHeight;
Evan Hahn
  • 12,147
  • 9
  • 41
  • 59
  • Evan, how would you do it on page reload? I mean when I get a new message it shows that one, with the scrolltop. But when I reload the conversation it shows the oldes message, so you either have to scroll down or send a new message to get to the newest. – Sean Magyar Oct 28 '15 at 11:44
  • @SzilardMagyar You can run the "new chat message" code when the page loads. Here's an example that might help: https://gist.github.com/EvanHahn/f3abde4987334a46bce6 – Evan Hahn Oct 28 '15 at 17:50
  • Evan, I pulled it off. For first I put the line to the wrong place. – Sean Magyar Oct 29 '15 at 15:52
  • Have you tested this solution on a long list of elements? The div gets scrolled to a certain point and not to its end. – Neli Chakarova Oct 03 '16 at 19:54
  • @NeliChakarova I don't think I did, sadly. – Evan Hahn Oct 05 '16 at 17:45
  • 1
    I ended up using CSS following this [sample](https://jsfiddle.net/ajiths4u/u9dzyvct/). Unfortunately, I lost the original so post – Neli Chakarova Oct 06 '16 at 07:14
1

For a scrolling part refer to jQuery Scroll to bottom of page/iframe

As for line brakes - it should be like this automatically.

Community
  • 1
  • 1
David Jashi
  • 4,490
  • 1
  • 21
  • 26