Search code examples
javascriptpackery

Packery not initialized - Cannot call methods, i.e. $().packery("bindDraggabillyEvents")


I am trying to combine packery and dragabilly on an image upload function. I am initializing both of them in the same function but get the error that packery has not initialized. I have tried splitting up my code into two functions, one to handle the image upload and dragabilly. The other to handle packery but I still get the same issue. Right now the images are getting pulled in and are draggable but packery isn't getting initialized. Any help is appreciated!

JS

function handleFileSelect(evt) {
  var files = evt.target.files;

  // Loop through the FileList and render image files as thumbnails.
  for (var i = 0, f; f = files[i]; i++) {
    if (!f.type.match('image.*')) {
      continue; // only accept image files
    }

    var reader = new FileReader();
    // Closure to capture the file information.
    reader.onload = (function(uploadedFile) {
      return function(e) {
        var $container = $(".packery")
        var div = document.createElement('div');

        div.className = "col-3 image-item";
        div.innerHTML = ['<div class="handle"></div><img class="thumb" src="', e.target.result,
                                '" title="', escape(uploadedFile.name), '"/>'].join('');
        document.getElementById('packery').insertBefore(div, null);
        var draggie = new Draggabilly (div, {
          handle: '.handle'
        });

      $container.packery('bindDraggabillyEvents', draggie);
     };
    })(f);

   // Read in the image file as a data URL.
   reader.readAsDataURL(f);
  } // end of for loop
} // handlefileselect end

$('#files').change(handleFileSelect);

HTML

<input id="files" multiple="true" name="files[]" type="file" />
<div class="packery" id="packery"></div>

Solution

  • Packery is not being initialized in the code you have provided. See http://packery.metafizzy.co/#getting-started for information on how to initialize.

    The following line does not initialize packery!

     $container.packery('bindDraggabillyEvents', draggie);
    

    I suggest adding this line of code before the last line (where the on change event handler is assigned):

    $('.packery').packery();