Skip to content

using javascript to scroll primefaces treetable or other scrollable component

craigmcchesney edited this page Jun 30, 2020 · 1 revision

I needed to scroll a primefaces treetable to the selected tree node, set in Java code as the "action" for a search commandbutton. I was surprised that I could not do this directly in primefaces, but did find a Javascript approach, after much investigation, and thus the documentation here for future reference.

The javascript function is called by the oncomplete attribute of the search commandbutton. This is different code than for the main CDB machine design list view scroll to selected node, because the main list view is not scrollable, so the desired node is displayed on the page and it’s just a matter of scrolling to that part of the page. In this case, the list itself is scrollable, and therefore the desired item is not displayed on the page. So it’s a matter of using javascript to scroll the scrollable body for the component. The challenging part was finding the right selector to pass to find() to get the scrollable part of the table component.

Here is the current function body:

                        <script type="text/javascript">
                            function scrollToSelectedNode(treeWidgetVar) {
                                var selectedElement = treeWidgetVar.jq.find('.ui-state-highlight');
                                if ((selectedElement.position() != undefined)) {
                                     var scrollPanel = treeWidgetVar.jq.find('.ui-treetable-scrollable-body');
                                     var scrollTopPos = selectedElement.position().top;
                                     scrollPanel.animate({ scrollTop: scrollTopPos});
                                }
                            }
                        </script>

And the corresponding button and treetable xhtml:

    <p:treeTable id='treeTableId'
                 widgetVar="treeTableWidget"
                 scrollable="#{true}"
                 scrollHeight="65vh"
                 value="#{wizardController.machineDesignTreeEndpoint1}"
                 selectionMode="single"
                 selection="#{wizardController.selectionEndpoint1}"
                 var="itemElementTreeListObject"/>

    <p:commandButton id="searchButtonId" 
                     oncomplete="scrollToSelectedNode(PF('treeTableWidget'));"
                     ajax="true"
                     update="@form:treeTableId" 
                     action="#{wizardController.searchEndpoint1()}"/>  
Clone this wiki locally