SVG jQuery UI Drag Example

Add a custom drag handler to jQuery UI draggable in order to drag jQuery-SVG elements around

by mcannon

HTML

<script src="https://rawgit.com/kbwood/svg/master/jquery.svg.js"></script>
<link rel="stylesheet" href="https://rawgit.com//kbwood/svg/master/jquery.svg.css">
<h1>SVG jQuery UI Drag Example</h1>

<div  id="svg_canvas">
    <svg>
        <circle id="blue" cx="150" cy="150" r="50" fill="blue" />
    </svg>
</div>

CSS

#svg_canvas {
    position: relative;
    height: 400px;
    width: 400px;
    background: #ffc;
}

JavaScript

function drawInto(svg) {
    svg.circle(100, 100, 50, {
        id: 'red',
        fill: 'red'
    });
}

$('#svg_canvas').svg({
    onLoad: drawInto
});

$('#red, #blue').draggable({
    drag: function(event, ui) {
        var position = ui.position;
        var $circle = $(this);
        var radius = $circle.prop('r').baseVal.value;

        $circle.prop('cx').baseVal.value = position.left + radius;
        $circle.prop('cy').baseVal.value = position.top + radius;
    }
});