Restrict the Drag operation of an Element to its Container using the jQuery UI

I saw a question on one of the forums where a user asked if it was possible to restrict the drag operation of an element to its container using jQuery. In fact, achieving this is quite simple using the jQuery UI. Here’s how:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<
head>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</
script>
<
title>Drag an Element within its container</title>
<
meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<
style type="text/css">
#outer
{
width: 400px;
height:400px;
border: solid 1px black;
}
#ele{
width:70px;
height:70px;
background-color:Blue;
}
</style>
</
head>
<
body>
<
div id="outer">
<
p id="ele"></p>
</
div>
<
script type="text/javascript">
$(function() {
var opt = {
cursor: "move",
containment: "parent"
};
$("#ele").draggable(opt);
});
</script>
</
body>
</
html>

I have declared an element ‘ele’ inside a container ‘outer’. Observe how I have set the containment option to “parent”. This constrains dragging to within the bounds of the specified element or region.

Now when you will view the page, you will observe that the ‘ele’ element cannot exceed the boundary of its container ‘outer’.

Note: I have included the JavaScript and CSS in the same page. Ideally, these resources should be kept in separate folders

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: