Add div element on click and make it draggable using jquery
HTML
<div id="layoutSpace">
Click and drag the box.
</div>
CSS
#layoutSpace{
width:450px;
height:450px;
background:#F4F4F4;
margin:auto;
position:relative;
}
.dbox{
width:100px;
height:100px;
border:1px solid #C9C9C9;
position:absolute;
}
JavaScript
$('#layoutSpace').click(function(e){
var offset = $(this).offset();
areaBox = 50;//to center the mouse point
mouseX = (e.pageX - offset.left - areaBox );
mouseY = (e.pageY - offset.top - areaBox );
$('#layoutSpace').append('<div class="dbox" style="left:'+ mouseX +'px;top:'+ mouseY +'px;"></div>');
//run the draggable function
runTheDrag();
});
MainlayoutX = $('#layoutSpace').offset().left; //Get main layout of the mainContainer
MainlayoutY = $('#layoutSpace').offset().top; //Get main layout of the mainContainer
//function for draggable box
function runTheDrag(){
$(".dbox").draggable({
containment: '#layoutSpace',
scroll: false,
drag: function(){
var offset = $(this).offset();
var left = offset.left - MainlayoutX;
var top = offset.top - MainlayoutY;
$(".dbox .xAxis").val(left);
$(".dbox .yAxis").val(top);
}
});
}