-
Notifications
You must be signed in to change notification settings - Fork 20
using javascript to scroll a primefaces non scrollable datatable
Here is a javascript function to scroll a primefaces datatable to the selected node that is displayed on the page. That is, the datatable is not defined as "scrollable" and we can assume that the selected item is displayed on the page, and we just need to scroll to it.
In this case, the selection is made externally, by an ajax event handler for selection in a tree view. That is, when we select an item in the tree component, we want to select the corresponding datatable row.
The script code:
<script type="text/javascript"> function scrollToSelectedNode() { selectedRows = document.getElementsByClassName('ui-widget-content ui-datatable-selectable ui-state-highlight'); if (selectedRows.length > 0) { row = selectedRows[0]; row.scrollIntoView({'behavior': 'smooth', 'block': 'center'}); } } </script>
The corresponding xhtml code includes the ajax event handler nested inside the tree component tag, and the corresponding datatable tag. The listener for the ajax event sets the selection in the datatable:
<p:tree> <p:ajax event="select" listener="#{wizardController.treeSelectionChanged}" update="@form:#{rootViewId}ValidatePanel" oncomplete="scrollToSelectedNode();"/> </p:tree> <p:dataTable id="dataTableId" value="#{wizardController.rows}" rendered="true" var="row" rowKey="#{row.name}" selectionMode="single" selection="#{wizardController.selectedTableRow}"/>
Here is the java code that sets the selection in the datatable:
public void treeSelectionChanged(NodeSelectEvent event) { CdbEntity selectedItem = (CdbEntity)event.getTreeNode().getData(); if (getRows().contains(selectedItem)) { setSelectedTableRow(selectedItem); } } public void setSelectedTableRow(CdbEntity entity) { selectedTableRow = entity; }