Earlier using javascript code to make an element draggable was very hard and moreover cross-browser version working of code was very difficult.
The following code shows how to make an element draggable inside its parent element by using jQuery UI library. With jQuery drag and drop features we hardly have to do any hard coding. To make a element draggable simply call the draggable()
method on it. Here's a simple example:
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div id="divX" style="border:solid 1px;background:#eee; height:200px;">
<span style="cursor:pointer">Click anywhere on me to see cursor type...</span>
</div>
<script>
$("#divX span").draggable({containment: 'parent'});
</script>
</body>
</html>
You can also pass many options insode draggable() function to customize the behaviour of the draggable element.
Here i have used option containment and passed value parent, this make the draggable element to be dragged inside its parent element. If you will not provide this option then by default you can drag the element anywhere inside the page.
Explore it with more options and see what can you get.
0 Comment(s)