Resizable and Draggable in jQuery with Example

Introduction:
This article explains how to do Resizing and Dragging of a DIV using jQuery UI. I will show you the demo of a DIV, which can be resized by pulling up the edges and also dragged here and there.




Step 1: Setting up jQuery UI and CSS
We need to install jQuery UI library first in order to do resizing/dragging. Add following lines in your HEAD of html document.

<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.js"></script>
<link rel="stylesheet" type="text/css"
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css"/>

Note that we have imported jquery and jquery-ui library. Also, to use Resizable we must import jquery-ui.css file. This stylesheet will be used by resizable to add resize corner and other internal styles.

Step 2: Write jQuery to Resize and Drag
For the demo we will define a small DIV which we will make resizable and draggable.


<div id="resizeDiv"></div>

Now just add following jQuery code in your document.

$('#resizeDiv')
    .draggable()
    .resizable();

The beauty of jQuery is that we can simply chain the function calling. First we called .draggable() function that makes the DIV draggable and then we called resizable().
You may want to define callback functions on start/stop/resize events. To do so we simply define:


$('#resizeDiv')
    .resizable({
        start: function(e, ui) {
            alert('resizing started');
        },
        resize: function(e, ui) {
         
        },
        stop: function(e, ui) {
            alert('resizing stopped');
        }
    });

Note that the callback function gets two arguments. First is event object and next is ui.
The ui object has the following fields:

    ui.helper – a jQuery object containing the helper element
    ui.originalPosition – {top, left} before resizing started
    ui.originalSize – {width, height} before resizing started
    ui.position – {top, left} current position
    ui.size – {width, height} current size


DEMO:-
Drag and Resize the following box.
---------------------------------------------------------------------------------------------------------------------------------
jQuery Resizable and Draggable Demo - ViralPatel.net
Move Me!!... Resize Me!!...
---------------------------------------------------------------------------------------------------------------------------------
Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment