The dragging behavior can be limited with some configurable constraints.
In this recipe, we will see how to drag an element, either horizontally or vertically, on a grid or inside a certain section of the page.
The next example demonstrates three draggable panels and one draggable image. The first panel can be dragged only horizontally, the second one only vertically, and the third panel is dragged on a grid. Dragging on a grid means the dragging helper snaps to a grid—every specific x
and y
pixel. The image is placed within an h:panelGroup
tag, which acts as a container for dragging. The image cannot go outside this container.
<p:panel id="hpnl" header="Only horizontal draggable panel"> I can be only dragged horizontally. </p:panel> <p:draggable for="hpnl" axis="x"/> <p:panel id="vpnl" header="Only vertical draggable panel"> I can be only dragged vertically </p:panel> <p:draggable for="vpnl" axis="y"/> <p:panel id="gpnl" header="Draggable panel in grid [40,50]"> I can be only dragged in a grid </p:panel> <p:draggable for="gpnl" grid="40,50"/> The image below can be only dragged within its parent's boundaries <h:panelGroup layout="block" styleClass="dragContainer ui-widget-content"> <h:graphicImage id="pic" library="images" name="logo.png"/> </h:panelGroup> <p:draggable for="pic" containment="parent"/>
The following screenshot shows the result achieved with the preceding code snippet. Especially, we can see that the image has stayed in its boundaries although the cursor has gone outside.
Horizontal or vertical dragging is possible by setting the axis
attribute as axis="x"
or axis="y"
, which means that the draggable element can be dragged only horizontally or only vertically, respectively.
Dragging on a grid is defined by the grid
attribute. The value for dragging on a grid takes comma-separated dimensions. For instance, grid="40,50"
means that the draggable element can be dragged in only 40 pixel steps horizontally and 50 vertically.
The containment
attribute constraints dragging within the boundaries of the containment element. Possible string values are parent
, document
, window
, and [x1, y1, x2, y2]
. The setting containment="parent"
in the preceding example means that the draggable element cannot go outside its parent.
Refer to the Snapping to the edges of nearest elements recipe to learn about the more advanced features of Draggable
.
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 every Servlet 3.x compatible application server, such as JBoss WildFly or Apache TomEE.
The showcase for the recipe is available at http://localhost:8080/pf-cookbook/views/chapter8/advancedDraggable.jsf
.