Sticking a component when scrolling

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.

How to do it…

We would like to stick a select menu with a label as shown in this screenshot:

How to do it…

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"/>

How it works…

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.

Note

There are no visual styles of sticky; however, the ui-shadow and ui-sticky classes are applied to the target when the position is fixed. Therefore, we set box-shadow: none on h:panelGrid in order to remove the visible shadow around the grid.

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.

There's more…

The header of p:dataTable can also be fixed at the top of the visible viewport when scrolling:

<p:dataTable stickyHeader="true" ...>
  ...
</p:dataTable>

PrimeFaces Cookbook Showcase application

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.254.44