What’s the best option for storing size and position information for resizable draggable divs? I have a page that will have many resizable movable divs. The state of the divs (top, left, width, height) will have to be restored when the user visits the page again. I did one test with cookies that worked, but this might not be right if there are many divs. I tested jquery data, but there seems to be a problem. This code returns undefined for data retrieved at the next page load.
<script>
function getdivinfo() {
var position = $( "#compage" ).position();
var width = $( "#compage" ).width();
var height= $( "#compage" ).height();
var left = position.left;
var top = position.top;
$( "#compage" ).data("layout", { "dleft": left, "dtop": top, "dwidth": width, "dheight": height });
}
function divlayout() {
var restleft = $( "#compage" ).data("layout").dleft;
var resttop = $( "#compage" ).data("layout").dtop;
var restwidth = $( "#compage" ).data("layout").dwidth;
var restheight = $( "#compage" ).data("layout").dheight;
$( "#compage" ).css("top", resttop);
$( "#compage" ).css("left", restleft);
$( "#compage" ).css("width", restwidth);
$( "#compage" ).css("height", restheight);
}
</script>
HTML information
<body onload="divlayout();">
<div class="demo">
<div id="compage" class="ui-widget-content">
<h3 class="ui-widget-header">Sample</h3>
</div>
<a href="#" onclick="getdivinfo();">Get div info</a>
<a href="#" onclick="savedivinfo();"> Save div info</a>
</div><!-- End demo -->
JQuery data does not persist, it is only valid as long as the HTML is loaded. Local storage would be the best solution, but it’s not supported by older browsers, and there are still many of them out there. Cookies are a good solution, eventually use less cookies with longer values, or many cookies with smaller values, depending on which limit you think you will hit.
Obviously, saving it server side would be great 🙂