1

I have aura component inside community page and I need automatically scroll to bottom inside the component when I receive new records. The component is used like chat. How to implement it?

1 Answer 1

0

We have add handler of aura:doneRendering event and attribute of last scroll height if we want to scroll to top and stay above when we receive new records (prevent autoscrolling):

<aura:component controller="ChatController" 
    implements="forceCommunity:availableForAllPageTypes,force:appHostable">

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler event="aura:doneRendering" action="{!c.doneRendering}"/>

    <aura:attribute name="lastScrollHeight" type="Double" default="0" />
    <aura:attribute name="message" type="String" />
    <aura:attribute name="messages" type="ChatController.MessageWrapper[]" /> 

    <section role="log" class="slds-chat chatSection" aura:id="chatSectionId">
        <aura:iteration items="{!v.messages}" var="msg">
            <c:ChatItem messageWrapper="{!msg}" />
        </aura:iteration>
    </section>

</aura:component>

el.offsetHeight is the static value, equals to the height of DOM element in pixels, and never changes.

el.scrollHeight is Y-position of the scroll bar in pixels

el.scrollTop is el.scrollHeight - el.offsetHeight

doneRendering : function(component) {
        try {
            var el = component.find('chatSectionId');
            if (el) {
                el = el.getElement();

                if (component.get('v.lastScrollHeight') == 0) {
                    component.set('v.lastScrollHeight', el.scrollHeight);
                }

                if (el.scrollTop >= (component.get('v.lastScrollHeight') - el.offsetHeight)) {
                    if (el.scrollHeight > component.get('v.lastScrollHeight')) {
                        el.scrollTop = el.scrollHeight - el.offsetHeight;
                        component.set('v.lastScrollHeight', el.scrollHeight);
                    }
                }
            }
        } catch (e) { }
    }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .