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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: