Objectives and Outcomes

In this tutorial we are going to learn about draggable function in jqueryUI and also about the constraints that can be used with the draggable function. The example for the same is given below:

Drag me anywhere on this page !!!



Now we can drag the above box anywhere on the page.The code for the above example is:


HTML code:

<html>
<head>
<title>jQuery UI Draggable</title>
<link href="jquery-ui.min.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
</head>
<body>
<div id="dragbox">
<p>Drag me anywhere on this page !!!</p>
</div>
</body>
</html>


CSS stylesheet:

<style>
#dragbox 
{
width: 150px; 
height: 150px; 
padding: 0.5em; 
background:#585858;
color:#FFF;
text-align:center;
}
</style>






Javascript

<script>
$(function() 
{
$( "#dragbox" ).draggable();
});
</script>


In the above example we have used only draggable function without constraints. Now we are going to use constraints with draggable function in examples below.

You can drag me only within this div.


The text in the above div can be dragged inside the div itself as we used containment constraint in draggable function.

Javascript:

<script>
$(function(){
$("#div4 span").draggable 
({
containment : "#div4"
});
});
</script>


You can drag me only along x axis.


The text in the above div can be dragged in x-direction only as we have used axis="x" constraint in draggable function.

Javascript:

<script>
$(function(){
$("#dragbox2 span").draggable 
({
axis : "x"
});
});
</script>