The Sticky
component is used to make another component stick to the top of the page once a user has scrolled past it. Hence, the sticky
component requires a target component to keep it in the viewport on scroll.
In this recipe, we will demonstrate the usage of the p:sticky
tag.
We would like to stick a select menu with a label as shown in this screenshot:
The select menu and the label are placed within h:panelGrid
, which acts as the target component:
<h:panelGrid id="langGrid" columns="2" style="box-shadow: none;"> <p:outputLabel for="lang" value="Language: "/> <p:selectOneMenu id="lang"> <f:selectItem itemLabel="English" itemValue="en"/> <f:selectItem itemLabel="German" itemValue="de"/> <f:selectItem itemLabel="French" itemValue="fr"/> </p:selectOneMenu> </h:panelGrid> ... <p:sticky target="langGrid"/>
The component to be sticked is referenced via the target
attribute. In the example, the target
attribute points to the ID of h:panelGrid
. If the component sticks, its position is changed to fixed by setting the position: fixed
style. This happens automatically on scrolling down. The fixed position gets removed on scrolling up when the component is visible at its original location.
There is also the margin
attribute. It defines the offset between the sticked component and the top of the page. The default value is 0
.
The header of p:dataTable
can also be fixed at the top of the visible viewport when scrolling:
<p:dataTable stickyHeader="true" ...> ... </p:dataTable>
This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on application servers compatible with Servlet 3.x, such as JBoss WildFly and Apache TomEE.
The showcase for the recipe is available at http://localhost:8080/pf-cookbook/views/chapter11/sticking.jsf
.