How do I save the position of draggable & resizeable elements?

Sharon picture Sharon · Mar 14, 2011 · Viewed 28.9k times · Source

I'm building a site which allows users to create an html page which can then be saved and shared on another site. I want them to be able to resize and drag the page elements. I can do this using jQuery, but I'm not sure how I then save that so that when the page is viewed elsewhere, it looks the same.

I haven't decided yet how to store the page info, but what I'm thinking is that I can store each element in the database along with its absolute position, and its contents. Does that sound like a good plan?

If so, how do I get the position for the div to pass to the php so that it can be saved?

Thanks.

Answer

Fran Verona picture Fran Verona · Mar 14, 2011

JQueryUI Resizable has an event called resize that you can use:

var resposition = '';

$('#divresize').resizable({
   //options...
   resize: function(event,ui){
      resposition = ui.position;
   }
});

The same occurs with JQueryUI Draggable and its event drag:

var dragposition = '';

$('#divdrag').draggable({
   // other options...
   drag: function(event,ui){
      dragposition = ui.position;
   }
});

resposition and dragposition is going to be arrays. You can see it working here: http://jsbin.com/uvuzi5

EDIT: using a form, you can save dragposition and resposition into hidden inputs

var inputres = '<input type="hidden" id="resposition" value="'+resposition.left+','+resposition.top+'"/>'
$('#myform').append(inputres);
var inputdrag = '<input type="hidden" id="dragposition" value="'+dragposition.left+','+dragposition.top+'"/>'
$('#myform').append(inputdrag);

And in your PHP file to handle the form:

$dragposition = $_GET['dragposition'];
$resposition = $_GET['resposition'];
$dragposition = explode(',',$dragposition);
$resposition = explode(',',$resposition);

Finally, both variables should be arrays with top and left attributes:

$dragposition => [top,left] attributes from draggable
$resposition => [top,left] attributes from resizable