Reputation: 618
I'm trying to make a DIV for a chat box scroll when overflowed, but unfortunately it's stopping short and I don't know why. Here is my code.
Can someone tell me what's wrong and how to fix it? Right now what happens is that it will scroll down for a little while, but then it will stop scrolling. I've been stuck on this problem for almost an hour now.
Upvotes: 1
Views: 685
Reputation: 253486
While I'm not, currently, sure why your own attempt fails (though I'd guess it's a problem with the variable CHATBOX_ID
, but that's only because you've not shown where it's coming from), this version works. Albeit with a couple of assumptions (which I'll explain later):
var chatContentHeight, scrollVal;
var chatHeight = $('#chat').height();
$('#message').keyup(
function(e) {
chatContentHeight = 0;
if (e.keyCode == '13') { // assuming you want messages submitted on hitting 'enter'
newMsg = $(this).val();
$('<div />').text(newMsg).appendTo('#chat');
$(this).val('');
$('#chat > div').each(
function() {
chatContentHeight = chatContentHeight + $(this).outerHeight();
});
if (chatContentHeight > chatHeight) { // checking whether or not scrolling is needed
scrollVal = (chatContentHeight - chatHeight); // defines the amount to scroll
$('#chat').scrollTop(scrollVal);
}
}
});
My assumptions are:
div
s to contain the messages, I'd personally prefer to use a dl
or ol
, but it seemed to complicate the demo a little to use those elements, though they're perfectly possible to use.If you'd like an explanation (or, at least, if you'd like to help us to be able to offer an explanation) you'll need to at least post your full jQuery/JavaScript or link to a live demo that reproduces your problem (either on your own server or at JS Fiddle or similar).
References:
Upvotes: 2