Greg
Greg

Reputation: 21899

jQuery UI draggable - constrain inner element within parent when inner element is larger than parent

I am trying to achieve this effect with jQuery UI - very much like the way you crop an image on Facebook:

http://blog.creonfx.com/examples/javascript/facebook-cropping-mootools.html

Here is a very simple test case in HTML (an img within a div):

<div>
    <img src="fat_cat.jpg">
</div>

and here is the logic that seems fit for the purpose - however it is unfinished:

$("img").draggable({ drag: dragHandler });

function dragHandler(event, ui) {
    var x = event.target.x - event.target.parentNode.offsetLeft;
    var y = event.target.offsetTop;

    if(x > 0) {
        // How to constrain the movement here?
    }
    if(x < -(event.target.offsetWidth -
            event.target.parentNode.offsetWidth)) {
    }
    if(y > 0) {
    }
    if(y < -(event.target.offsetHeight - 
             event.target.parentNode.offsetHeight)) {
    }

    $("p").text(x + ", " + y);
}

My first attempts were to modify the offsetLeft & offsetTop variables, in all their multiple access points, but nothing seems to be working for me.

Here is a jsFiddle with what is explained above: http://jsfiddle.net/g105b/FdkBK/

Upvotes: 6

Views: 3203

Answers (1)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

You can actually do this with an inner container whose width/height is calculated to only allow the image to travel a certain distance. Of course you also have to position the inner container appropriately.

Here is my go at it:

Markup:

<div id="outer"> <!-- position: relative -->
    <div id="inner"> <!-- position: absolute -->   
        <img src="">
    </div>
</div>

Script:

var img = $("img").draggable({ containment: '#inner'}),
    h = img.height(),
    w = img.width(),
    outer = $('#outer'),
    oH = outer.height(),
    oW = outer.width(),
    iH = h + (h - oH),
    iW = w + (w - oW),
    iT = '-' + ((iH - oH)/2) + 'px',
    iL = '-' + ((iW - oW)/2) + 'px';

$('#inner').css({ width: iW, height: iH, top: iT, left: iL });

Upvotes: 6

Related Questions