Search code examples
javascriptjquerycssjquery-uijquery-draggable

jQuery UI Draggable Snap Restore not working


I'm in the proccess of building a window manager for a project i'm working on this window manager uses jQuery UI Draggable and Resizable and for the most part i have it working.

The problem i seem to be having is with a feature that i need to implement witch is the windows 7/8 window snap to the top, left or right. now i have the snapping working but then when a use drags the window i want it to restore to it's old size but the possition need to be centered to the mouse point and for some reason jQuery UI seem's to be restoring the postion to the drag start location once i re-size it.

DEMO http://jsfiddle.net/t5zqcdtm/1/

how to test this is if you grab one of the 2 open windows and drag them so the mouse is within 3px of the top you will see an outline for full size then let go and the window will full size however then move you mouse to right left of the control buttons at the right of the title bar so just left of "_" and drag the window you will see the window position is not centered to the mouse

Code with problem is at Line 108:

var mode = $(ui.helper).data("mode");
var oldStyle = JSON.parse($(ui.helper).data("origin"));
newStyle = clone(oldStyle);
newStyle.left = e.pageX - (
parseInt(oldStyle.width.substring(0, oldStyle.width.length - 2)) / 2) + "px";
newStyle.top = e.clientY + "px";
console.log({
    old: oldStyle,
    new: newStyle
});
$(ui.helper).css(newStyle);
$(ui.helper).data("mode", "");

Could any one tell me why the window then jump to the top left


Solution

  • When draggable starts there's a calculation being made with where the click was made and the position and width of the element being dragged. The problem here seems to be that the click position is calculated before you resize the element, so the drag is then calculated with this click position.

    You can access this click position in the instance and modify it according to your need. For example you could determine if the click is outside the new width of the window and if so reposition accordingly. Like this:

    start: function (e, ui) {
                        ...
        //At the end of your start function
        //you check the actual position of the click
        var clickLeft = $(this).draggable('instance').offset.click.left;
        //If this click is out of the window, or in the top right icons
        if (clickLeft > ($(ui.helper).width() - 50)) {
            //You set the click left to wherever you need
            $(this).draggable('instance').offset.click.left = $(ui.helper).width() - 50;
       }
    
    }
    

    http://jsfiddle.net/u95ba45k/1/