Drag Zone

by Chan Wu

HTML

<button id="btn_add_y">add y</button>
<button id="btn_add_x">add x</button>
<button id="btn_add_fit">add fit</button>
<input type="text" id="left" size="6">
<input type="text" id="top" size="6">
<div class="container"></div>

CSS

.container {
    width: 200px;
    height: 200px;
    border: 2px solid red;
    position: relative;
}
.y {
    width: 200px;
    height: 500px;
    background: yellow;
    left: 0;
    top: 0;
    cursor: move;
}
.x {
    width: 500px;
    height: 200px;
    background: red;
    left: 0;
    top: 0;
    cursor: move;
}
.fit {
    width: 200px;
    height: 200px;
    background: blue;
    left: 0;
    top: 0;
    cursor: move;
}

JavaScript

console.clear();

var container = $('.container');

$('#btn_add_y').on('click', function () {
    container.html('<div class="y"></div>');
    container.find('> div').dragZone({
        topTarget: '#top',
        leftTarget: '#left'
    });
});

$('#btn_add_x').on('click', function () {
    container.html('<div class="x"></div>');
    container.find('> div').dragZone({
        topTarget: '#top',
        leftTarget: '#left'
    });
});

$('#btn_add_fit').on('click', function () {
    container.html('<div class="fit"></div>');
    container.find('> div').dragZone();
});

$.fn.dragZone = function(options) {
    return this.each(function() {
        var container = $(this).parent();
        var setting = $.extend({
            leftTarget: null,
            topTarget: null
        }, options);

        if ($(this).width() <= container.width() && $(this).height() <= container.height()) {
            return false;
        }

        if ($(this).width() > $(this).height()) {
            var type = 'x';
            var moveLimit = container.width() - $(this).width();
        } else {
            var moveLimit = container.height() - $(this).height();
            var type = 'y';
        }

        setPosition($(this));

        $(this).draggable({
            axis: type,
            stop: function() {
            setPosition($(this));

                switch (type) {
                    case 'x':
                        if ($(this).position().left > 0) {
                            $(this).stop().animate({
                                left: 0
                            }, function() {
                                setPosition($(this));
                            });
                        }

                        if ($(this).position().left < moveLimit) {
                            $(this).stop().animate({
                                left: moveLimit
                            }, function() {
                                setPosition($(this));
             ...