If you want to preserve the X/Y coordinates, you can store them in various ways. Whether it's local storage, cookies, or an API, the method doesn't matter as long as you capture the information.
<div id="drag">
<div>
<div>
<div>
<p>This div is draggable</p>
<button id="saveMe">Save</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
if (local.get('divOffset')) {
//check if local storage already has your offset. and set it
$('#drag').css(local.get('divOffset'))
}
$('#drag').draggable();
$('#drag').on('click', '#saveMe', function () {
// we're listening for a click event on the saveMe button
var $drag = $('#drag'),
//assigning the #drag div jQ obj to a variable
offset = $drag.offset();
// grabbing the offset: Object {top: 157.5, left: 150}
local.set('divOffset', offset);
//save the offset(local storage)
});
});
function Local () {
return {
set : function (key, obj) {
localStorage.setItem(key, JSON.stringify(obj));
return obj;
},
get : function (key) {
var obj = {};
if (localStorage.getItem(key) !== 'undefined') {
obj = JSON.parse(localStorage.getItem(key));
}
return obj;
},
clear : function () {
localStorage.clear();
return this;
},
remove : function (key) {
localStorage.removeItem(key);
return this;
}
};
}
var local = Local();
</script>
Storing data in a database via an API ensures consistency across multiple devices, unlike local storage which is tied to a single machine. I have showcased local storage here for illustration purposes, but using an API for saving data is a more complex process.
Below is a custom getter/setter function I created for local storage management in the past.