Ember.js v0.9.7
HTML
<script src="https://github.com/downloads/emberjs/ember.js/ember-0.9.7.js"></script>
<script type="text/x-handlebars">
{{view App.MessagesView contentBinding="App.messages"}}
{{view App.MessageInputView}}
</script>
CSS
* {
box-sizing: border-box;
}
.messages-list {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: auto;
padding-bottom: 55px;
}
.message {
border-bottom: 1px solid #CCC;
padding: 5px;
}
.message-input {
position: absolute;
bottom: 0;
height: 50px;
width: 100%;
}
JavaScript
// How to scroll to the bottom when the page loads / when a new message is added
App = Ember.Application.create({});
App.Message = Ember.Object.extend({});
App.messages = Ember.ArrayController.create({
content: [],
addMessage: function(str) {
this.pushObject(App.Message.create({content: str}));
}
});
App.MessageInputView = Ember.TextArea.extend({
classNames: ["message-input"],
attributeBindings: ["placeholder"],
placeholder: "Enter a new message here",
insertNewline: function(e)
{
App.messages.addMessage(this.get("value"));
this.set("value", "");
window.scrollTo(0, document.body.scrollHeight)
}
});
App.MessageView = Ember.View.extend({
classNames: ["message"],
template: Ember.Handlebars.compile('{{content.content}}'),
// could do it here, fine for a new message
// but then it would happen ~100 times on initial load
didInsertElement: function() {
// scroll window to bottom
}
});
App.MessagesView = Ember.CollectionView.extend({
tagName: "ol",
classNames: ["messages-list"],
itemViewClass: "App.MessageView",
// can't do it here as the messages aren't loaded yet
// especially as the messages come in later via Ajax request
didInsertElement: function() {
// scroll window to bottom
}
});
App.messages.pushObject(App.Message.create({content: "How to get this to scroll to the bottom when the page loads and a new message is added?"}));
// add a load of messages to get us started
for (var i=1; i<100; i++) {
App.messages.pushObject(App.Message.create({content: "Message "+i}));
}