Josh Braun
Josh Braun

Reputation: 490

Center draggable div relative to cursor when the size of the div changes

I'm writing an application with draggable fields (the divs). Before these fields are placed they are one size but then once they are picked up and being dragged they change to their "final" size (the size can change at a later time too, but they stay the dragged size until it's changed manually later).

What I'm trying to do is center the div relative to the cursor when the div is being dragged.

I know about the cursorAt property of draggable objects, but it's not working when you drag the object for the first time. If you drag, drop, and drag again it will center correctly.

Fiddle demonstrating the issue.

$('div').draggable({
    start: function () {
        $(this)
            .css('height', (Math.floor((Math.random() * 250) + 100).toString() + 'px'))
            .css('width', (Math.floor((Math.random() * 250) + 100).toString() + 'px'));

        $(this).draggable('option', 'cursorAt', {
            top: parseInt($(this).css('height')) / 2,
            left: parseInt($(this).css('width')) / 2
        });
    }
});

Obviously that's just an example, but it demonstrates the point because it will never center the div relative to the cursor. I figured that since I'm setting the CSS first that it should be doing it correctly, but it doesn't.

I've also tried moving the changing of the size to the mousedown event in to make sure the CSS get's changed first (in case for some reason it wasn't...was just a way to make sure) but it still doesn't work correctly.

And I also tried calculating the new sizes first, and then using the variable to do the calculations instead of relying on the CSS values. Still didn't work.

Upvotes: 0

Views: 1098

Answers (1)

Downgoat
Downgoat

Reputation: 14371

Do you have to use the .draggable() from jQuery UI ?
I put together a jQuery plugin at http://pastebin.com/vCr0xuTz which auto centers like you need
You can then just use $('div').drag(); and that should center the div when the size changes.

JSFiddle: http://jsfiddle.net/blue11086/d06r990w/3/

Upvotes: 1

Related Questions