Monday, October 1, 2012

Drag and Resize Images using jQuery UI

Just the other day, I wanted to have the functionality to drag and resize an image on a HTML page using jQuery and jQuery UI.

Surprisingly, calling the usual draggable() and resizable() doesn't work as expected when applied on an img element, although it works perfectly for a div element.

After some digging into the jQuery UI code, I found the reason for this flawed functionality. It is because jQuery UI creates a wrapper div for the elements which cannot hold child nodes if resizable() function is applied on them.

The easiest and simplest way to get around this problem is to call the draggable() function on the implicitly created wrapper div.
The wrapper div’s class name is ui-wrapper.


A similiar solution can be used for canvas, textarea, input, select, button elements. The above solution works for multiple images on the page with class as "drag". 

Another common approach is to create a div element which contains the img element. The div and img elements are bound so that on resize of the div element, the img element is scaled up or down.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.