Reputation: 223
I'm building a basic real-time messaging app in Meteor and currently every time a message is created it is appended to the list of messages on the page & everything is working correctly. However once the contents of the messagesList div overflow (I've set it to scroll) I can no longer see the latest messages without scrolling down manually each time.
What is the 'Meteor way' of using callbacks to skip to the bottom automatically (e.g. with Jquery scrolltop) every time the messages list rerenders? I had a go at it in the messages list template helpers but I'm not getting a value returned on scrollTop and I can't figure out if it's my selectors or something to do with Meteor, i.e. where I am putting the code. So I'd really appreciate some pointers.
Here's what I have:
messagesList.html
<template name="messagesList">
<div class="pure-g-r content" id="layout">
<div class="pure-u-1" id="list">
{{#each messages}}
{{> messageItem}}
{{/each}}
</div>
</div>
</template>
messagesList.js:
Template.messagesList.helpers({
messages: function() {
return Messages.find();
}
});
Template.messagesList.rendered = function () {
console.log("scrolltop is " + $('#list').scrollTop);
// $('#list').scrollTop( $('#list').height() )
};
messageItem.html:
<template name="messageItem">
<div class="email-item email-item pure-g">
<div class="pure-u-3-4">
<p>
<strong>{{sentBy}}</strong><br>
{{msgText}}
</p>
</div>
</div>
</template>
MessageSubmit.html:
<template name="messageSubmit">
<form class="pure-form">
<input type="text" name="msg" class="pure-input-rounded">
<button type="submit" class="pure-button">Speak!</button>
</form>
</template>
messageSubmit.js:
Template.messageSubmit.events({
'submit form': function(e) {
e.preventDefault();
console.log('new comment created')
var user = Meteor.user();
var message = {
msgText: $(e.target).find('[name=msg]').val(),
sentBy: user.profile.name,
userId: user._id
}
message._id = Messages.insert(message);
$('.pure-input-rounded').val("");
}
});
main.css:
html, body {
height: 100%;
}
#layout {
max-height: 60%;
left: 20px;
top: 60px;
position: relative;
overflow: scroll;
padding-bottom: 60px;
}
h1 {
font-size: 2em !important;
}
.pure-form {
position: absolute;
left: 10px;
bottom: 20px;
}
Upvotes: 2
Views: 2187
Reputation: 21364
I don't think there is a particularly meteor way of doing this, but with this minor fix to your code it should work:
Template.messagesList.rendered = function () {
console.log("scrolltop is " + $('#list').scrollTop());
$('#list').scrollTop( $('#list').prop("scrollHeight") );
};
Upvotes: 1