Open iamgurjitsingh opened 10 years ago
Heya, It's going to vary wildly from app to app, but in my case, what I do is save a piece JSON per user, I store the id, the order, and the time in millis. My 'modules' can be different on each page, ie you could have A, B, C, D on one page and only A, C, D on the other, so if you save the new order, and now go back to the first page, you have B and C with order number 2, so then I use the millis to decide who wins and takes the second slot. My flow is like this:
Put the available modules on the page in any order, and spit out the JSON if available. Use the JSON to reorder the divs in the dom, before the users sees them. Fire up shapshift, all is good. User reorders the modules the way they want them. AJAX call to the server with the JSON containing simple objects like {id: x, order: x, millis: x} Store that away to use the next time they visit the page.
There's going to be a lot of way to do this, but that's how I'm doing it.
I've made it like this, hope someone can find it useful:
<div class="container">
<div class="ElementToDrag" data-block_name="firstBlock" data-sorting="0">
<!--content-->
</div>
<div class="ElementToDrag" data-block_name="secondBlock" data-sorting="1">
<!--content-->
</div>
</div>
<div id="save">Save</div>
$(document).ready(function() {
//updating order if you already have it in database
var jsonOrdering = JSON.parse('<?php echo $savedJsonOrdering; ?>'); //$savedJsonOrdering is actual JSON.stringify(elems), which is posted to server
for (var key in jsonOrdering ) {
$('.ElementToDrag[data-block_name="'+key+'"]').attr('data-sorting', jsonOrdering[key].order);
}
orderBlocks();
//after the DOM ordering is completed, we can init shapeshift
$('.container').shapeshift();
//sending results to server (to be saved in database)
//local storage can also be used
$('#save').click(function(){
var elems = getBlockOrder();
$.ajax({
url: "/save.php?page_id=1", /*page_id is used because you can have different ordering for each page */
method: 'POST',
dataType: "json",
data: 'data='+JSON.stringify(elems)
});
});
function getBlockOrder() {
var elements = new Object();
$('.ElementToDrag').each(function(i, elem){
var eName = elem.getAttribute('data-block_name');
elements[eName] = new Object();
elements[eName].order = i;
//set additional data if needed, like:
//elements[eName].visible = elem.getAttribute('data-visible');
});
return elements;
}
//Put blocks in correct position in DOM
function orderBlocks() {
var $wrapper = $('.container'),
$blocks = $('.ElementToDrag');
$blocks.sort(function(a,b){
var an = a.getAttribute('data-sorting'),
bn = b.getAttribute('data-sorting');
if(an > bn) {
return 1;
}
if(an < bn) {
return -1;
}
return 0;
});
$blocks.detach().appendTo($wrapper);
}
});
in save.php:
$savedJsonOrdering = $_POST['data'];
// ... save it as is...
Can anyone tell me how can we save order of elements affter drag & drog? Any Idea...