jQuery UI resizable - direction of operation

gruszczy picture gruszczy · Jul 16, 2009 · Viewed 10.7k times · Source

How can I determine the direction of resize operation? I tried googling that and found a ticket on jquery ui, that said it is fixed. But there is no doc on how to use it.

Answer

sixthgear picture sixthgear · Jul 16, 2009

Not sure if you meant that you'd like to constrain the resize operation to a particular axis, or if you'd like to know what direction the resize actually occurred in.

RaYell's answer works if you wanted to former. I'll discuss the latter.

If you set up a resizable like this:

var r = $("#resizable");
r.resizable();

Let's say you'd like to know what direction the resize occurred in after the user releases the mouse button. Let's bind a function to the resize stop event:

r.bind('resizestop', function(event, ui) {
    // determine resize deltas
    var delta_x = ui.size.width - ui.originalSize.width;
    var delta_y = ui.size.height - ui.originalSize.height;
}

Using the passed ui object, we can determine the relative change in size by subtracting the new size from the old size. After that, you can use delta_x and delta_y however you wish. Let's build a string that corresponds to one of the handles.

r.bind('resizestop', function(event, ui) {

    // determine resize deltas
    var delta_x = ui.size.width - ui.originalSize.width;
    var delta_y = ui.size.height - ui.originalSize.height;

    // build direction string
    var dir = '';

    if (delta_y > 0) { 
        dir += 's';
    } else if (delta_y < 0) { 
        dir += 'n';         
    }      

    if (delta_x > 0) { 
        dir += 'e';
    } else if (delta_x < 0) { 
        dir += 'w';
    }

    // do something with this string
    alert(dir);        
});

Note that this will not necessarily return which handle was actually used to perform the resize if you have handles on both sides of the element, only it's net direction.