Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onsen UI: Automatic scroll with ons-list

Tags:

onsen-ui

i want to program a chat in WhatsApp style. The latest news will be shown below, and for new messages to be automatically scrolled down. Can anyone help me how I can realize the automatic scrolling with ons-list?

<ons-template id="chat.html">
    <ons-page ng-controller="ChatController">
        <ons-toolbar>
            <div class="left"><ons-back-button>Back</ons-back-button></div>
            <div class="center">Chat</div>
        </ons-toolbar>

        <ons-list style="margin-top: 10px" scroll-glue>
            <ons-list-item class="item" ng-repeat="msg in messages">
                <header>
                    <span class="item-title">{{msg.user}}</span>
                </header>
                <p class="item-desc">{{msg.msg}}</p>
            </ons-list-item>
        </ons-list>
    </ons-page>
</ons-template>
like image 969
quersumme Avatar asked Sep 03 '15 08:09

quersumme


1 Answers

I haven't used WhatsApp, but this might help. In an ons-page, you can use .page__content's scrollTop property for auto scroll. Like below. It uses jQuery for animation.

ons.bootstrap()
.controller('ChatController', function($scope, $timeout){
  $scope.messages = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
  $timeout(function(){
    $('.page__content').animate({scrollTop: $('.ons-list-inner').height()}, 2000)
    .animate({scrollTop: 0}, 2000);
  });
});
<link href="https://cdn.rawgit.com/OnsenUI/OnsenUI/1.3.8/build/css/onsen-css-components.css" rel="stylesheet"/>
<link href="https://cdn.rawgit.com/OnsenUI/OnsenUI/1.3.8/build/css/onsenui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdn.rawgit.com/OnsenUI/OnsenUI/1.3.8/build/js/angular/angular.min.js"></script>
<script src="https://cdn.rawgit.com/OnsenUI/OnsenUI/1.3.8/build/js/onsenui.min.js"></script>

<ons-navigator page="chat.html"></ons-navigator>

<ons-template id="chat.html">
    <ons-page ng-controller="ChatController">
        <ons-toolbar>
            <div class="left"><ons-back-button>Back</ons-back-button></div>
            <div class="center">Chat</div>
        </ons-toolbar>

        <ons-list style="margin-top: 10px" scroll-glue>
            <ons-list-item class="item" ng-repeat="msg in messages">
                <header>
                    <span class="item-title">{{msg.user}}</span>
                </header>
                <p class="item-desc">{{msg.msg}}</p>
            </ons-list-item>
        </ons-list>
    </ons-page>
</ons-template>
like image 140
cither Avatar answered Jan 02 '23 11:01

cither