$(function() {
var myItems = [{
id: "el-1",
label: "Administration",
position: {
top: 0,
left: 0
},
props: {
width: 90,
height: 90
}
},
{
id: "el-2",
label: "Canteen",
position: {
top: 0,
left: 102
},
props: {
width: 45,
height: 90
}
}, {
id: "el-3",
label: "Storage (Cold)",
position: {
top: 103,
left: 0
},
props: {
width: 90,
height: 25
}
}
];
function placeElem(dObj, $p) {
var item = $("<div>", {
id: dObj.id,
class: "placed draggable ui-widget-content",
width: dObj.props.width + "px",
height: dObj.props.height + "px"
}).html(dObj.label).appendTo($p);
item.css({
left: dObj.position.left + "px",
top: dObj.position.top + "px"
});
}
function getElPosition($el) {
var r = {
top: Math.round(parseInt($el.css("top").slice(0, -2))),
left: Math.round(parseInt($el.css("left").slice(0, -2)))
};
return r;
}
function log(h) {
$("#log").prepend(h);
}
function getJSON() {
// Get JSON data from Data Source and return it. Similar to 'myItems'
// Use placeElem() to load the data as eleemnts to page
}
function saveJSON() {
// Save JSON data, like myItems, to Data Source
// Iterate each element and use getElPosition() to build data
var items = $(".placed");
var data = [];
items.each(function(i, el) {
data.push({
id: $(el).attr("id"),
label: $(el).text().trim(),
position: getElPosition($(el)),
props: {
width: $(el).width(),
height: $(el).height()
}
});
});
var json = JSON.stringify(data);
console.log(data);
console.log(json);
}
$.each(myItems, function(key, item) {
log("<p>Adding " + item.id + ", left: " + item.position.left + ", top: " + item.position.top + "</p>");
placeElem(item, $("#containment-wrapper"));
var p = getElPosition($("#" + item.id));
log("<p>" + item.id + " position left: " + p.left + ", position top: " + p.top + "</p>");
});
$(".draggable").draggable({
containment: "parent",
start: function(e, ui) {
var p = getElPosition($(this));
log("<p>Drag Start " + $(this).attr("id") + " position left: " + p.left + ", position top: " + p.top + "</p>");
},
stop: function(e, ui) {
var p = getElPosition($(this));
log("<p>Drag Stop " + $(this).attr("id") + " position left: " + p.left + ", position top: " + p.top + "</p>");
}
});
});
.draggable {
width: 90px;
height: 90px;
padding: 0.5em;
float: left;
margin: 0;
font-size: 0.65em;
}
#containment-wrapper {
width: 65%;
height: 300px;
border: 2px solid #ccc;
padding: 0;
position: relative;
}
#containment-wrapper .placed {
position: absolute;
background: #999;
}
h3 {
clear: left;
}
#log {
font-size: .5em
}
#log p {
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="containment-wrapper">
</div>
<div id="log"></div>