jQuery and ASP.NET

January 18, 2010

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


Bookmark this link on del.icio.us (saved by 0 users)

Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter
Others Also Read..

comments

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

Copyright 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal