jQuery UI: Draggable

Draggable Elements

by TheFiddler

HTML

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.21/themes/base/jquery-ui.css">
<script src="http://jsplumb.org/js/1.3.4/jquery.jsPlumb-1.3.4-all.js"></script>
<div id="boundbox">
    <div id="div1" class="left"></div>
    <div id="div2" class="right" style="top:4em;left:20em;">2</div>
    <div id="div3" class="left" style="top:0em;left:10em;">3</div>
    <div id="div4" class="right" style="top:15em;left:20em;">4</div>
</div>

CSS

#div1 {
    width: 40px;
    height: 40px;
    background-color: red;
    border: 2px solid black;
    border-radius: 40px;
    cursor: pointer;
    position: relative;
    top: 160px;
    left: 160px;
}
#div4{background-color:red;width:50px;height:50px;position:absolute; }
#div2, #div3{background-color:green;width:50px;height:50px; position:absolute;}

#boundbox {
    border: 1px dashed black;
    width: 360px;
    height: 360px;
    background-color: #eee;
    margin-top: 20px;
    margin-left: 20px;
}

JavaScript

$(document).ready(function () {
    $("#div1").draggable({
        drag: function (e, ui) {

            var width = $('#boundbox').width();
            var height = $('#boundbox').height();

            var x = ui.position.left + $(this).width() / 2;
            var y = ui.position.top + $(this).height() / 2;

            var elteres = Math.abs(x - width / 2);
            var min_y = height * (elteres / (width / 2));
            if (y < min_y) y = min_y;

            if (x < 0) x = 0;
            if (y < 0) y = 0;
            if (x > width) x = width;
            if (y > height) y = height;

            ui.position.top = y - $(this).height() / 2;
            ui.position.left = x - $(this).width() / 2;
            jsPlumb.repaintEverything();
            
        },
        stop: function (e, ui) {
            //call jsplumb repaint
            jsPlumb.repaintEverything();
        }
    });
jsPlumb.draggable($(".left"));
jsPlumb.draggable($(".right"));
jsPlumb.connect({
    source: "div1",
    target: "div2",
    paintStyle: {
        lineWidth: 15,
        strokeStyle: 'rgb(243,230,18)'
    },
    endpointStyle: {
        fillStyle: 'rgb(243,229,0)'
    }
});
jsPlumb.connect({
    source: 'div3',
    target: 'div4',
    paintStyle: {
        lineWidth: 10,
        strokeStyle: 'rgba(0, 0, 200, 0.5)'
    },
    anchors: ["RightMiddle", "LeftMiddle"],
    endpoint: ["Rectangle", {
        width: 10,
        height: 8
    }]
});
jsPlumb.connect({
    source: 'div2',
    target: 'div3',
    paintStyle: {
        lineWidth: 8,
        strokeStyle: 'rgb(189,11,11)'
    },
    anchors: ["BottomCenter", "TopCenter"],
    endpoint: "Rectangle"
});

});