In order to get this done, we have to take into account the height of that new message and the height of the previous message. Inside Atom, we're going to go ahead and get that done, by first up adding a selector.
We're going to make a variable called newMessage, and this is going to store the selector for the last list item, the one that was just added before the call to scroll to bottom. I'm going to use jQuery to get this done, but instead of creating a new selector, we can actually build off of our previous one, messages, and we're going to call its children method:
function scrollToBottom () {
// Selectors
var message = jQuery('#message');
var newMessage = message.children();
This lets you write a selector specific to the children of the message, which means that we have all our list items so we could select our list items in another context, maybe we want to select all the children that are paragraphs. In our case, though, we're going to select the list items that are the last child using this last-child modifier:
var newMessage = messages.children('li:last-child');
Now we have just one item, the last list item in the list, and we can go ahead and get its height by making a variable called newMessageHeight, just next to the scrollHeight variable. We're going to set that equal to newMessage, and we're going to call its innerHeight method:
var scrollHeight = messages.prop('scrolHeight');
var newMessageHeight = newMessage.innerHeight();
This is going to calculate the height of the message taking into account the padding that we've also applied via CSS.
Now we need to take into account the height of the second-to-last message as well. To do that, we're going to create a variable lastMessageHeight, and we'll set it equal to newMessage, and we're going to call the prev method. This moves us to the previous child, so if we were at the last list item we are now at the second-to-last list item, and we can get its height by once again calling innerHeight:
var newMessageHeight = newMessage.innerHeight();
var lastMessageHeight = newMessage.prev().innerHeight();
Now we can account for both of these values inside our if statement as well. We're going to add them up, newMessageHeight, and we're also going to add lastMessageHeight taking that into account as we make our calculation:
function scrollToBottom() {
//selectors
var messages = jQuery('#messages');
//Heights
var clientHeight = messages.prop('clientHeight');
var scrollTop = messages.prop('scrollTop');
var scrollHeight = messages.prop('scrollHeight');
var newMessageHeight = newMessage.innerHeight();
var lastMessageHeight = newMessage.prev().innerHeight();
if(clientHeight + scrollTop + newMessageHeight + lastMessageHeight >= scrollHeight) {
console.log('Should scroll');
}
}
Now that our calculation is complete we can actually test out that things are working as expected. We should see Should scroll when we should scroll.