Search code examples
javascriptpackery

Packery Save order and reuse the order


Can anyone help me how to save the order of a packery elements while dragging. and then reorder the packery items in the saved order.? here is the code I used before

<div class="g_container">
           <?php foreach($_POST['old_img'] as $key=>$val){ ?>
               <div class="item" tabindex="<?php echo $key; ?>">
                <img src="../img/gallery/<?php echo $val; ?>">
               </div>
             <?php } ?>
           </div>

here is the javascript code.

<script src="../js/packery.pkgd.min.js"></script>
    <script src="../js/draggabilly.js"></script>
    <script>
    $(document).ready(function(){
   // Packery // 
 var $container = $('.g_container').packery({
   gutter:10
 });

 $container.find('.item').each( function( i, itemElem ) {
   // make element draggable with Draggabilly
   var draggie = new Draggabilly( itemElem );
   // bind Draggabilly events to Packery
   $container.packery( 'bindDraggabillyEvents', draggie );
 });
  $("#save_gallery").on("click",function(){
   var page_name=$("#pn").val();
   var gallery=$(".gallery").html();
   $.ajax({
     data:"gallery="+gallery+"&pn="+page_name,
     method:"POST",
     cache:false,
     url:"ajax/save-gallery.php",
     success:function(data){
      alert(data);
      //location.href="page-galleries.php";
     }
    });
  });
 });
</script>

Thanks in advance. :)


Solution

  • Use this function I created for the your problem:

    var $itemElems = $($container.packery('getItemElements'));
    orderItems = function() {
        var itemElems = $($container.packery('getItemElements'));
        $(itemElems).each(function(i, itemElem) {
            $(itemElem).attr('data-module-index', i); 
            // adds a data attribute called data-module-index to the element  
            //   and makes the value its actual index.
        });
    };
    orderItems();